| 1 |
//=======- PtrTypesSemantics.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 "PtrTypesSemantics.h" |
| 10 |
#include "ASTUtils.h" |
| 11 |
#include "clang/AST/Attr.h" |
| 12 |
#include "clang/AST/CXXInheritance.h" |
| 13 |
#include "clang/AST/Decl.h" |
| 14 |
#include "clang/AST/DeclCXX.h" |
| 15 |
#include "clang/AST/ExprCXX.h" |
| 16 |
#include "clang/AST/StmtVisitor.h" |
| 17 |
#include "clang/Analysis/DomainSpecific/CocoaConventions.h" |
| 18 |
#include <optional> |
| 19 |
|
| 20 |
using namespace clang; |
| 21 |
|
| 22 |
namespace { |
| 23 |
|
| 24 |
bool hasPublicMethodInBaseClass(const CXXRecordDecl *R, StringRef NameToMatch) { |
| 25 |
assert(R); |
| 26 |
assert(R->hasDefinition()); |
| 27 |
|
| 28 |
for (const CXXMethodDecl *MD : R->methods()) { |
| 29 |
const auto MethodName = safeGetName(MD); |
| 30 |
if (MethodName == NameToMatch && MD->getAccess() == AS_public) |
| 31 |
return true; |
| 32 |
} |
| 33 |
return false; |
| 34 |
} |
| 35 |
|
| 36 |
} // namespace |
| 37 |
|
| 38 |
namespace clang { |
| 39 |
|
| 40 |
std::optional<const clang::CXXRecordDecl *> |
| 41 |
hasPublicMethodInBase(const CXXBaseSpecifier *Base, StringRef NameToMatch) { |
| 42 |
assert(Base); |
| 43 |
|
| 44 |
const Type *T = Base->getType().getTypePtrOrNull(); |
| 45 |
if (!T) |
| 46 |
return std::nullopt; |
| 47 |
|
| 48 |
const CXXRecordDecl *R = T->getAsCXXRecordDecl(); |
| 49 |
if (!R) { |
| 50 |
auto CT = Base->getType().getCanonicalType(); |
| 51 |
if (auto *TST = dyn_cast<TemplateSpecializationType>(CT)) { |
| 52 |
auto TmplName = TST->getTemplateName(); |
| 53 |
if (!TmplName.isNull()) { |
| 54 |
if (auto *TD = TmplName.getAsTemplateDecl()) |
| 55 |
R = dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl()); |
| 56 |
} |
| 57 |
} |
| 58 |
if (!R) |
| 59 |
return std::nullopt; |
| 60 |
} |
| 61 |
if (!R->hasDefinition()) |
| 62 |
return std::nullopt; |
| 63 |
|
| 64 |
return hasPublicMethodInBaseClass(R, NameToMatch) ? R : nullptr; |
| 65 |
} |
| 66 |
|
| 67 |
std::optional<bool> isSmartPtrCompatible(const CXXRecordDecl *R, |
| 68 |
StringRef IncMethodName, |
| 69 |
StringRef DecMethodName) { |
| 70 |
assert(R); |
| 71 |
|
| 72 |
R = R->getDefinition(); |
| 73 |
if (!R) |
| 74 |
return std::nullopt; |
| 75 |
|
| 76 |
bool hasRef = hasPublicMethodInBaseClass(R, IncMethodName); |
| 77 |
bool hasDeref = hasPublicMethodInBaseClass(R, DecMethodName); |
| 78 |
if (hasRef && hasDeref) |
| 79 |
return true; |
| 80 |
|
| 81 |
CXXBasePaths Paths; |
| 82 |
Paths.setOrigin(const_cast<CXXRecordDecl *>(R)); |
| 83 |
|
| 84 |
bool AnyInconclusiveBase = false; |
| 85 |
const auto hasPublicRefInBase = [&](const CXXBaseSpecifier *Base, |
| 86 |
CXXBasePath &) { |
| 87 |
auto hasRefInBase = clang::hasPublicMethodInBase(Base, IncMethodName); |
| 88 |
if (!hasRefInBase) { |
| 89 |
AnyInconclusiveBase = true; |
| 90 |
return false; |
| 91 |
} |
| 92 |
return (*hasRefInBase) != nullptr; |
| 93 |
}; |
| 94 |
|
| 95 |
hasRef = hasRef || R->lookupInBases(hasPublicRefInBase, Paths, |
| 96 |
/*LookupInDependent =*/true); |
| 97 |
if (AnyInconclusiveBase) |
| 98 |
return std::nullopt; |
| 99 |
|
| 100 |
Paths.clear(); |
| 101 |
const auto hasPublicDerefInBase = [&](const CXXBaseSpecifier *Base, |
| 102 |
CXXBasePath &) { |
| 103 |
auto hasDerefInBase = clang::hasPublicMethodInBase(Base, DecMethodName); |
| 104 |
if (!hasDerefInBase) { |
| 105 |
AnyInconclusiveBase = true; |
| 106 |
return false; |
| 107 |
} |
| 108 |
return (*hasDerefInBase) != nullptr; |
| 109 |
}; |
| 110 |
hasDeref = hasDeref || R->lookupInBases(hasPublicDerefInBase, Paths, |
| 111 |
/*LookupInDependent =*/true); |
| 112 |
if (AnyInconclusiveBase) |
| 113 |
return std::nullopt; |
| 114 |
|
| 115 |
return hasRef && hasDeref; |
| 116 |
} |
| 117 |
|
| 118 |
std::optional<bool> isRefCountable(const clang::CXXRecordDecl *R) { |
| 119 |
return isSmartPtrCompatible(R, "ref", "deref"); |
| 120 |
} |
| 121 |
|
| 122 |
std::optional<bool> isCheckedPtrCapable(const clang::CXXRecordDecl *R) { |
| 123 |
return isSmartPtrCompatible(R, "incrementCheckedPtrCount", |
| 124 |
"decrementCheckedPtrCount"); |
| 125 |
} |
| 126 |
|
| 127 |
bool isRefType(const std::string &Name) { |
| 128 |
return Name == "Ref" || Name == "RefAllowingPartiallyDestroyed" || |
| 129 |
Name == "RefPtr" || Name == "RefPtrAllowingPartiallyDestroyed"; |
| 130 |
} |
| 131 |
|
| 132 |
bool isRetainPtrOrOSPtr(const std::string &Name) { |
| 133 |
return Name == "RetainPtr" || Name == "RetainPtrArc" || |
| 134 |
Name == "OSObjectPtr" || Name == "OSObjectPtrArc"; |
| 135 |
} |
| 136 |
|
| 137 |
bool isCheckedPtr(const std::string &Name) { |
| 138 |
return Name == "CheckedPtr" || Name == "CheckedRef"; |
| 139 |
} |
| 140 |
|
| 141 |
bool isOwnerPtr(const std::string &Name) { |
| 142 |
return isRefType(Name) || isCheckedPtr(Name) || Name == "unique_ptr" || |
| 143 |
Name == "UniqueRef" || Name == "LazyUniqueRef"; |
| 144 |
} |
| 145 |
|
| 146 |
bool isSmartPtrClass(const std::string &Name) { |
| 147 |
return isRefType(Name) || isCheckedPtr(Name) || isRetainPtrOrOSPtr(Name) || |
| 148 |
Name == "WeakPtr" || Name == "WeakPtrFactory" || |
| 149 |
Name == "WeakPtrFactoryWithBitField" || Name == "WeakPtrImplBase" || |
| 150 |
Name == "WeakPtrImplBaseSingleThread" || Name == "ThreadSafeWeakPtr" || |
| 151 |
Name == "ThreadSafeWeakOrStrongPtr" || |
| 152 |
Name == "ThreadSafeWeakPtrControlBlock" || |
| 153 |
Name == "ThreadSafeRefCountedAndCanMakeThreadSafeWeakPtr"; |
| 154 |
} |
| 155 |
|
| 156 |
bool isCtorOfRefCounted(const clang::FunctionDecl *F) { |
| 157 |
assert(F); |
| 158 |
const std::string &FunctionName = safeGetName(F); |
| 159 |
|
| 160 |
return isRefType(FunctionName) || FunctionName == "adoptRef" || |
| 161 |
FunctionName == "UniqueRef" || FunctionName == "makeUniqueRef" || |
| 162 |
FunctionName == "makeUniqueRefWithoutFastMallocCheck" |
| 163 |
|
| 164 |
|| FunctionName == "String" || FunctionName == "AtomString" || |
| 165 |
FunctionName == "UniqueString" |
| 166 |
// FIXME: Implement as attribute. |
| 167 |
|| FunctionName == "Identifier"; |
| 168 |
} |
| 169 |
|
| 170 |
bool isCtorOfCheckedPtr(const clang::FunctionDecl *F) { |
| 171 |
assert(F); |
| 172 |
return isCheckedPtr(safeGetName(F)); |
| 173 |
} |
| 174 |
|
| 175 |
bool isCtorOfRetainPtrOrOSPtr(const clang::FunctionDecl *F) { |
| 176 |
const std::string &FunctionName = safeGetName(F); |
| 177 |
return FunctionName == "RetainPtr" || FunctionName == "adoptNS" || |
| 178 |
FunctionName == "adoptCF" || FunctionName == "retainPtr" || |
| 179 |
FunctionName == "RetainPtrArc" || FunctionName == "adoptNSArc" || |
| 180 |
FunctionName == "adoptOSObject" || FunctionName == "adoptOSObjectArc"; |
| 181 |
} |
| 182 |
|
| 183 |
bool isCtorOfSafePtr(const clang::FunctionDecl *F) { |
| 184 |
return isCtorOfRefCounted(F) || isCtorOfCheckedPtr(F) || |
| 185 |
isCtorOfRetainPtrOrOSPtr(F); |
| 186 |
} |
| 187 |
|
| 188 |
bool isStdOrWTFMove(const clang::FunctionDecl *F) { |
| 189 |
auto FnName = safeGetName(F); |
| 190 |
auto *Namespace = F->getParent(); |
| 191 |
if (!Namespace) |
| 192 |
return false; |
| 193 |
auto *TUDeck = Namespace->getParent(); |
| 194 |
if (!isa_and_nonnull<TranslationUnitDecl>(TUDeck)) |
| 195 |
return false; |
| 196 |
auto NsName = safeGetName(Namespace); |
| 197 |
return (NsName == "WTF" || NsName == "std") && FnName == "move"; |
| 198 |
} |
| 199 |
|
| 200 |
template <typename Predicate> |
| 201 |
static bool isPtrOfType(const clang::QualType T, Predicate Pred) { |
| 202 |
QualType type = T; |
| 203 |
while (!type.isNull()) { |
| 204 |
if (auto *SpecialT = type->getAs<TemplateSpecializationType>()) { |
| 205 |
auto *Decl = SpecialT->getTemplateName().getAsTemplateDecl(); |
| 206 |
return Decl && Pred(Decl->getNameAsString()); |
| 207 |
} else if (auto *DTS = type->getAs<DeducedTemplateSpecializationType>()) { |
| 208 |
auto *Decl = DTS->getTemplateName().getAsTemplateDecl(); |
| 209 |
return Decl && Pred(Decl->getNameAsString()); |
| 210 |
} else |
| 211 |
break; |
| 212 |
} |
| 213 |
return false; |
| 214 |
} |
| 215 |
|
| 216 |
bool isRefOrCheckedPtrType(const clang::QualType T) { |
| 217 |
return isPtrOfType( |
| 218 |
T, [](auto Name) { return isRefType(Name) || isCheckedPtr(Name); }); |
| 219 |
} |
| 220 |
|
| 221 |
bool isRetainPtrOrOSPtrType(const clang::QualType T) { |
| 222 |
return isPtrOfType(T, [](auto Name) { return isRetainPtrOrOSPtr(Name); }); |
| 223 |
} |
| 224 |
|
| 225 |
bool isOwnerPtrType(const clang::QualType T) { |
| 226 |
return isPtrOfType(T, [](auto Name) { return isOwnerPtr(Name); }); |
| 227 |
} |
| 228 |
|
| 229 |
std::optional<bool> isUncounted(const QualType T) { |
| 230 |
if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) { |
| 231 |
if (auto *Decl = Subst->getAssociatedDecl()) { |
| 232 |
if (isRefType(safeGetName(Decl))) |
| 233 |
return false; |
| 234 |
} |
| 235 |
} |
| 236 |
return isUncounted(T->getAsCXXRecordDecl()); |
| 237 |
} |
| 238 |
|
| 239 |
std::optional<bool> isUnchecked(const QualType T) { |
| 240 |
if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) { |
| 241 |
if (auto *Decl = Subst->getAssociatedDecl()) { |
| 242 |
if (isCheckedPtr(safeGetName(Decl))) |
| 243 |
return false; |
| 244 |
} |
| 245 |
} |
| 246 |
return isUnchecked(T->getAsCXXRecordDecl()); |
| 247 |
} |
| 248 |
|
| 249 |
void RetainTypeChecker::visitTranslationUnitDecl( |
| 250 |
const TranslationUnitDecl *TUD) { |
| 251 |
IsARCEnabled = TUD->getLangOpts().ObjCAutoRefCount; |
| 252 |
DefaultSynthProperties = TUD->getLangOpts().ObjCDefaultSynthProperties; |
| 253 |
} |
| 254 |
|
| 255 |
void RetainTypeChecker::visitTypedef(const TypedefDecl *TD) { |
| 256 |
auto QT = TD->getUnderlyingType(); |
| 257 |
if (!QT->isPointerType()) |
| 258 |
return; |
| 259 |
|
| 260 |
auto PointeeQT = QT->getPointeeType(); |
| 261 |
const RecordType *RT = PointeeQT->getAsCanonical<RecordType>(); |
| 262 |
if (!RT) { |
| 263 |
if (TD->hasAttr<ObjCBridgeAttr>() || TD->hasAttr<ObjCBridgeMutableAttr>()) { |
| 264 |
RecordlessTypes.insert(TD->getASTContext() |
| 265 |
.getTypedefType(ElaboratedTypeKeyword::None, |
| 266 |
/*Qualifier=*/std::nullopt, TD) |
| 267 |
.getTypePtr()); |
| 268 |
} |
| 269 |
return; |
| 270 |
} |
| 271 |
|
| 272 |
for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) { |
| 273 |
if (Redecl->getAttr<ObjCBridgeAttr>() || |
| 274 |
Redecl->getAttr<ObjCBridgeMutableAttr>()) { |
| 275 |
CFPointees.insert(RT); |
| 276 |
return; |
| 277 |
} |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
bool RetainTypeChecker::isUnretained(const QualType QT, bool ignoreARC) { |
| 282 |
if (ento::cocoa::isCocoaObjectRef(QT) && (!IsARCEnabled || ignoreARC)) |
| 283 |
return true; |
| 284 |
if (auto *RT = dyn_cast_or_null<RecordType>( |
| 285 |
QT.getCanonicalType()->getPointeeType().getTypePtrOrNull())) |
| 286 |
return CFPointees.contains(RT); |
| 287 |
return RecordlessTypes.contains(QT.getTypePtr()); |
| 288 |
} |
| 289 |
|
| 290 |
std::optional<bool> isUncounted(const CXXRecordDecl* Class) |
| 291 |
{ |
| 292 |
// Keep isRefCounted first as it's cheaper. |
| 293 |
if (!Class || isRefCounted(Class)) |
| 294 |
return false; |
| 295 |
|
| 296 |
std::optional<bool> IsRefCountable = isRefCountable(Class); |
| 297 |
if (!IsRefCountable) |
| 298 |
return std::nullopt; |
| 299 |
|
| 300 |
return (*IsRefCountable); |
| 301 |
} |
| 302 |
|
| 303 |
std::optional<bool> isUnchecked(const CXXRecordDecl *Class) { |
| 304 |
if (!Class || isCheckedPtr(Class)) |
| 305 |
return false; // Cheaper than below |
| 306 |
return isCheckedPtrCapable(Class); |
| 307 |
} |
| 308 |
|
| 309 |
std::optional<bool> isUncountedPtr(const QualType T) { |
| 310 |
if (T->isPointerType() || T->isReferenceType()) { |
| 311 |
if (auto *CXXRD = T->getPointeeCXXRecordDecl()) |
| 312 |
return isUncounted(CXXRD); |
| 313 |
} |
| 314 |
return false; |
| 315 |
} |
| 316 |
|
| 317 |
std::optional<bool> isUncheckedPtr(const QualType T) { |
| 318 |
if (T->isPointerType() || T->isReferenceType()) { |
| 319 |
if (auto *CXXRD = T->getPointeeCXXRecordDecl()) |
| 320 |
return isUnchecked(CXXRD); |
| 321 |
} |
| 322 |
return false; |
| 323 |
} |
| 324 |
|
| 325 |
std::optional<bool> isGetterOfSafePtr(const CXXMethodDecl *M) { |
| 326 |
assert(M); |
| 327 |
|
| 328 |
if (isa<CXXMethodDecl>(M)) { |
| 329 |
const CXXRecordDecl *calleeMethodsClass = M->getParent(); |
| 330 |
auto className = safeGetName(calleeMethodsClass); |
| 331 |
auto method = safeGetName(M); |
| 332 |
|
| 333 |
if (isCheckedPtr(className) && (method == "get" || method == "ptr")) |
| 334 |
return true; |
| 335 |
|
| 336 |
if ((isRefType(className) && (method == "get" || method == "ptr")) || |
| 337 |
((className == "String" || className == "AtomString" || |
| 338 |
className == "AtomStringImpl" || className == "UniqueString" || |
| 339 |
className == "UniqueStringImpl" || className == "Identifier") && |
| 340 |
method == "impl")) |
| 341 |
return true; |
| 342 |
|
| 343 |
if (isRetainPtrOrOSPtr(className) && method == "get") |
| 344 |
return true; |
| 345 |
|
| 346 |
// Ref<T> -> T conversion |
| 347 |
// FIXME: Currently allowing any Ref<T> -> whatever cast. |
| 348 |
if (isRefType(className)) { |
| 349 |
if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(M)) { |
| 350 |
auto QT = maybeRefToRawOperator->getConversionType(); |
| 351 |
auto *T = QT.getTypePtrOrNull(); |
| 352 |
return T && (T->isPointerType() || T->isReferenceType()); |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
if (isCheckedPtr(className)) { |
| 357 |
if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(M)) { |
| 358 |
auto QT = maybeRefToRawOperator->getConversionType(); |
| 359 |
auto *T = QT.getTypePtrOrNull(); |
| 360 |
return T && (T->isPointerType() || T->isReferenceType()); |
| 361 |
} |
| 362 |
} |
| 363 |
|
| 364 |
if (isRetainPtrOrOSPtr(className)) { |
| 365 |
if (auto *maybeRefToRawOperator = dyn_cast<CXXConversionDecl>(M)) { |
| 366 |
auto QT = maybeRefToRawOperator->getConversionType(); |
| 367 |
auto *T = QT.getTypePtrOrNull(); |
| 368 |
return T && (T->isPointerType() || T->isReferenceType() || |
| 369 |
T->isObjCObjectPointerType()); |
| 370 |
} |
| 371 |
} |
| 372 |
} |
| 373 |
return false; |
| 374 |
} |
| 375 |
|
| 376 |
bool isRefCounted(const CXXRecordDecl *R) { |
| 377 |
assert(R); |
| 378 |
if (auto *TmplR = R->getTemplateInstantiationPattern()) { |
| 379 |
// FIXME: String/AtomString/UniqueString |
| 380 |
const auto &ClassName = safeGetName(TmplR); |
| 381 |
return isRefType(ClassName); |
| 382 |
} |
| 383 |
return false; |
| 384 |
} |
| 385 |
|
| 386 |
bool isCheckedPtr(const CXXRecordDecl *R) { |
| 387 |
assert(R); |
| 388 |
if (auto *TmplR = R->getTemplateInstantiationPattern()) { |
| 389 |
const auto &ClassName = safeGetName(TmplR); |
| 390 |
return isCheckedPtr(ClassName); |
| 391 |
} |
| 392 |
return false; |
| 393 |
} |
| 394 |
|
| 395 |
bool isRetainPtrOrOSPtr(const CXXRecordDecl *R) { |
| 396 |
assert(R); |
| 397 |
if (auto *TmplR = R->getTemplateInstantiationPattern()) |
| 398 |
return isRetainPtrOrOSPtr(safeGetName(TmplR)); |
| 399 |
return false; |
| 400 |
} |
| 401 |
|
| 402 |
bool isSmartPtr(const CXXRecordDecl *R) { |
| 403 |
assert(R); |
| 404 |
if (auto *TmplR = R->getTemplateInstantiationPattern()) |
| 405 |
return isSmartPtrClass(safeGetName(TmplR)); |
| 406 |
return false; |
| 407 |
} |
| 408 |
|
| 409 |
bool isPtrConversion(const FunctionDecl *F) { |
| 410 |
assert(F); |
| 411 |
if (isCtorOfRefCounted(F)) |
| 412 |
return true; |
| 413 |
|
| 414 |
// FIXME: check # of params == 1 |
| 415 |
const auto FunctionName = safeGetName(F); |
| 416 |
if (FunctionName == "getPtr" || FunctionName == "WeakPtr" || |
| 417 |
FunctionName == "dynamicDowncast" || FunctionName == "downcast" || |
| 418 |
FunctionName == "checkedDowncast" || FunctionName == "bit_cast" || |
| 419 |
FunctionName == "uncheckedDowncast" || FunctionName == "bitwise_cast" || |
| 420 |
FunctionName == "bridge_cast" || FunctionName == "bridge_id_cast" || |
| 421 |
FunctionName == "dynamic_cf_cast" || FunctionName == "checked_cf_cast" || |
| 422 |
FunctionName == "dynamic_objc_cast" || |
| 423 |
FunctionName == "checked_objc_cast") |
| 424 |
return true; |
| 425 |
|
| 426 |
auto ReturnType = F->getReturnType(); |
| 427 |
if (auto *Type = ReturnType.getTypePtrOrNull()) { |
| 428 |
if (auto *AttrType = dyn_cast<AttributedType>(Type)) { |
| 429 |
if (auto *Attr = AttrType->getAttr()) { |
| 430 |
if (auto *AnnotateType = dyn_cast<AnnotateTypeAttr>(Attr)) { |
| 431 |
if (AnnotateType->getAnnotation() == "webkit.pointerconversion") |
| 432 |
return true; |
| 433 |
} |
| 434 |
} |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
return false; |
| 439 |
} |
| 440 |
|
| 441 |
bool isTrivialBuiltinFunction(const FunctionDecl *F) { |
| 442 |
if (!F || !F->getDeclName().isIdentifier()) |
| 443 |
return false; |
| 444 |
auto Name = F->getName(); |
| 445 |
return Name.starts_with("__builtin") || Name == "__libcpp_verbose_abort" || |
| 446 |
Name.starts_with("os_log") || Name.starts_with("_os_log"); |
| 447 |
} |
| 448 |
|
| 449 |
bool isSingleton(const NamedDecl *F) { |
| 450 |
assert(F); |
| 451 |
// FIXME: check # of params == 1 |
| 452 |
if (auto *MethodDecl = dyn_cast<CXXMethodDecl>(F)) { |
| 453 |
if (!MethodDecl->isStatic()) |
| 454 |
return false; |
| 455 |
} |
| 456 |
const auto &NameStr = safeGetName(F); |
| 457 |
StringRef Name = NameStr; // FIXME: Make safeGetName return StringRef. |
| 458 |
return Name == "singleton" || Name.ends_with("Singleton"); |
| 459 |
} |
| 460 |
|
| 461 |
// We only care about statements so let's use the simple |
| 462 |
// (non-recursive) visitor. |
| 463 |
class TrivialFunctionAnalysisVisitor |
| 464 |
: public ConstStmtVisitor<TrivialFunctionAnalysisVisitor, bool> { |
| 465 |
|
| 466 |
// Returns false if at least one child is non-trivial. |
| 467 |
bool VisitChildren(const Stmt *S) { |
| 468 |
for (const Stmt *Child : S->children()) { |
| 469 |
if (Child && !Visit(Child)) |
| 470 |
return false; |
| 471 |
} |
| 472 |
|
| 473 |
return true; |
| 474 |
} |
| 475 |
|
| 476 |
template <typename StmtOrDecl, typename CheckFunction> |
| 477 |
bool WithCachedResult(const StmtOrDecl *S, CheckFunction Function) { |
| 478 |
auto CacheIt = Cache.find(S); |
| 479 |
if (CacheIt != Cache.end()) |
| 480 |
return CacheIt->second; |
| 481 |
|
| 482 |
// Treat a recursive statement to be trivial until proven otherwise. |
| 483 |
auto [RecursiveIt, IsNew] = RecursiveFn.insert(std::make_pair(S, true)); |
| 484 |
if (!IsNew) |
| 485 |
return RecursiveIt->second; |
| 486 |
|
| 487 |
bool Result = Function(); |
| 488 |
|
| 489 |
if (!Result) { |
| 490 |
for (auto &It : RecursiveFn) |
| 491 |
It.second = false; |
| 492 |
} |
| 493 |
RecursiveIt = RecursiveFn.find(S); |
| 494 |
assert(RecursiveIt != RecursiveFn.end()); |
| 495 |
Result = RecursiveIt->second; |
| 496 |
RecursiveFn.erase(RecursiveIt); |
| 497 |
Cache[S] = Result; |
| 498 |
|
| 499 |
return Result; |
| 500 |
} |
| 501 |
|
| 502 |
public: |
| 503 |
using CacheTy = TrivialFunctionAnalysis::CacheTy; |
| 504 |
|
| 505 |
TrivialFunctionAnalysisVisitor(CacheTy &Cache) : Cache(Cache) {} |
| 506 |
|
| 507 |
bool IsFunctionTrivial(const Decl *D) { |
| 508 |
if (auto *FnDecl = dyn_cast<FunctionDecl>(D)) { |
| 509 |
if (FnDecl->isVirtualAsWritten()) |
| 510 |
return false; |
| 511 |
} |
| 512 |
return WithCachedResult(D, [&]() { |
| 513 |
if (auto *CtorDecl = dyn_cast<CXXConstructorDecl>(D)) { |
| 514 |
for (auto *CtorInit : CtorDecl->inits()) { |
| 515 |
if (!Visit(CtorInit->getInit())) |
| 516 |
return false; |
| 517 |
} |
| 518 |
} |
| 519 |
const Stmt *Body = D->getBody(); |
| 520 |
if (!Body) |
| 521 |
return false; |
| 522 |
return Visit(Body); |
| 523 |
}); |
| 524 |
} |
| 525 |
|
| 526 |
bool IsStatementTrivial(const Stmt *S) { |
| 527 |
auto CacheIt = Cache.find(S); |
| 528 |
if (CacheIt != Cache.end()) |
| 529 |
return CacheIt->second; |
| 530 |
bool Result = Visit(S); |
| 531 |
Cache[S] = Result; |
| 532 |
return Result; |
| 533 |
} |
| 534 |
|
| 535 |
bool VisitStmt(const Stmt *S) { |
| 536 |
// All statements are non-trivial unless overriden later. |
| 537 |
// Don't even recurse into children by default. |
| 538 |
return false; |
| 539 |
} |
| 540 |
|
| 541 |
bool VisitAttributedStmt(const AttributedStmt *AS) { |
| 542 |
// Ignore attributes. |
| 543 |
return Visit(AS->getSubStmt()); |
| 544 |
} |
| 545 |
|
| 546 |
bool VisitCompoundStmt(const CompoundStmt *CS) { |
| 547 |
// A compound statement is allowed as long each individual sub-statement |
| 548 |
// is trivial. |
| 549 |
return WithCachedResult(CS, [&]() { return VisitChildren(CS); }); |
| 550 |
} |
| 551 |
|
| 552 |
bool VisitCoroutineBodyStmt(const CoroutineBodyStmt *CBS) { |
| 553 |
return WithCachedResult(CBS, [&]() { return VisitChildren(CBS); }); |
| 554 |
} |
| 555 |
|
| 556 |
bool VisitReturnStmt(const ReturnStmt *RS) { |
| 557 |
// A return statement is allowed as long as the return value is trivial. |
| 558 |
if (auto *RV = RS->getRetValue()) |
| 559 |
return Visit(RV); |
| 560 |
return true; |
| 561 |
} |
| 562 |
|
| 563 |
bool VisitDeclStmt(const DeclStmt *DS) { return VisitChildren(DS); } |
| 564 |
bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(DS); } |
| 565 |
bool VisitIfStmt(const IfStmt *IS) { |
| 566 |
return WithCachedResult(IS, [&]() { return VisitChildren(IS); }); |
| 567 |
} |
| 568 |
bool VisitForStmt(const ForStmt *FS) { |
| 569 |
return WithCachedResult(FS, [&]() { return VisitChildren(FS); }); |
| 570 |
} |
| 571 |
bool VisitCXXForRangeStmt(const CXXForRangeStmt *FS) { |
| 572 |
return WithCachedResult(FS, [&]() { return VisitChildren(FS); }); |
| 573 |
} |
| 574 |
bool VisitWhileStmt(const WhileStmt *WS) { |
| 575 |
return WithCachedResult(WS, [&]() { return VisitChildren(WS); }); |
| 576 |
} |
| 577 |
bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(SS); } |
| 578 |
bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(CS); } |
| 579 |
bool VisitDefaultStmt(const DefaultStmt *DS) { return VisitChildren(DS); } |
| 580 |
|
| 581 |
// break, continue, goto, and label statements are always trivial. |
| 582 |
bool VisitBreakStmt(const BreakStmt *) { return true; } |
| 583 |
bool VisitContinueStmt(const ContinueStmt *) { return true; } |
| 584 |
bool VisitGotoStmt(const GotoStmt *) { return true; } |
| 585 |
bool VisitLabelStmt(const LabelStmt *) { return true; } |
| 586 |
|
| 587 |
bool VisitUnaryOperator(const UnaryOperator *UO) { |
| 588 |
// Unary operators are trivial if its operand is trivial except co_await. |
| 589 |
return UO->getOpcode() != UO_Coawait && Visit(UO->getSubExpr()); |
| 590 |
} |
| 591 |
|
| 592 |
bool VisitBinaryOperator(const BinaryOperator *BO) { |
| 593 |
// Binary operators are trivial if their operands are trivial. |
| 594 |
return Visit(BO->getLHS()) && Visit(BO->getRHS()); |
| 595 |
} |
| 596 |
|
| 597 |
bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { |
| 598 |
// Compound assignment operator such as |= is trivial if its |
| 599 |
// subexpresssions are trivial. |
| 600 |
return VisitChildren(CAO); |
| 601 |
} |
| 602 |
|
| 603 |
bool VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { |
| 604 |
return VisitChildren(ASE); |
| 605 |
} |
| 606 |
|
| 607 |
bool VisitConditionalOperator(const ConditionalOperator *CO) { |
| 608 |
// Ternary operators are trivial if their conditions & values are trivial. |
| 609 |
return VisitChildren(CO); |
| 610 |
} |
| 611 |
|
| 612 |
bool VisitAtomicExpr(const AtomicExpr *E) { return VisitChildren(E); } |
| 613 |
|
| 614 |
bool VisitStaticAssertDecl(const StaticAssertDecl *SAD) { |
| 615 |
// Any static_assert is considered trivial. |
| 616 |
return true; |
| 617 |
} |
| 618 |
|
| 619 |
bool VisitCallExpr(const CallExpr *CE) { |
| 620 |
if (!checkArguments(CE)) |
| 621 |
return false; |
| 622 |
|
| 623 |
auto *Callee = CE->getDirectCallee(); |
| 624 |
if (!Callee) |
| 625 |
return false; |
| 626 |
|
| 627 |
if (isPtrConversion(Callee)) |
| 628 |
return true; |
| 629 |
|
| 630 |
const auto &Name = safeGetName(Callee); |
| 631 |
|
| 632 |
if (Callee->isInStdNamespace() && |
| 633 |
(Name == "addressof" || Name == "forward" || Name == "move")) |
| 634 |
return true; |
| 635 |
|
| 636 |
if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" || |
| 637 |
Name == "WTFReportBacktrace" || |
| 638 |
Name == "WTFCrashWithSecurityImplication" || Name == "WTFCrash" || |
| 639 |
Name == "WTFReportAssertionFailure" || Name == "isMainThread" || |
| 640 |
Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" || |
| 641 |
Name == "isWebThread" || Name == "isUIThread" || |
| 642 |
Name == "mayBeGCThread" || Name == "compilerFenceForCrash" || |
| 643 |
isTrivialBuiltinFunction(Callee)) |
| 644 |
return true; |
| 645 |
|
| 646 |
return IsFunctionTrivial(Callee); |
| 647 |
} |
| 648 |
|
| 649 |
bool VisitGCCAsmStmt(const GCCAsmStmt *AS) { |
| 650 |
return AS->getAsmString() == "brk #0xc471"; |
| 651 |
} |
| 652 |
|
| 653 |
bool |
| 654 |
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) { |
| 655 |
// Non-type template paramter is compile time constant and trivial. |
| 656 |
return true; |
| 657 |
} |
| 658 |
|
| 659 |
bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) { |
| 660 |
return VisitChildren(E); |
| 661 |
} |
| 662 |
|
| 663 |
bool VisitPredefinedExpr(const PredefinedExpr *E) { |
| 664 |
// A predefined identifier such as "func" is considered trivial. |
| 665 |
return true; |
| 666 |
} |
| 667 |
|
| 668 |
bool VisitOffsetOfExpr(const OffsetOfExpr *OE) { |
| 669 |
// offsetof(T, D) is considered trivial. |
| 670 |
return true; |
| 671 |
} |
| 672 |
|
| 673 |
bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) { |
| 674 |
if (!checkArguments(MCE)) |
| 675 |
return false; |
| 676 |
|
| 677 |
bool TrivialThis = Visit(MCE->getImplicitObjectArgument()); |
| 678 |
if (!TrivialThis) |
| 679 |
return false; |
| 680 |
|
| 681 |
auto *Callee = MCE->getMethodDecl(); |
| 682 |
if (!Callee) |
| 683 |
return false; |
| 684 |
|
| 685 |
auto Name = safeGetName(Callee); |
| 686 |
if (Name == "ref" || Name == "incrementCheckedPtrCount") |
| 687 |
return true; |
| 688 |
|
| 689 |
std::optional<bool> IsGetterOfRefCounted = isGetterOfSafePtr(Callee); |
| 690 |
if (IsGetterOfRefCounted && *IsGetterOfRefCounted) |
| 691 |
return true; |
| 692 |
|
| 693 |
// Recursively descend into the callee to confirm that it's trivial as well. |
| 694 |
return IsFunctionTrivial(Callee); |
| 695 |
} |
| 696 |
|
| 697 |
bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE) { |
| 698 |
if (!checkArguments(OCE)) |
| 699 |
return false; |
| 700 |
auto *Callee = OCE->getCalleeDecl(); |
| 701 |
if (!Callee) |
| 702 |
return false; |
| 703 |
// Recursively descend into the callee to confirm that it's trivial as well. |
| 704 |
return IsFunctionTrivial(Callee); |
| 705 |
} |
| 706 |
|
| 707 |
bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { |
| 708 |
if (auto *Expr = E->getExpr()) { |
| 709 |
if (!Visit(Expr)) |
| 710 |
return false; |
| 711 |
} |
| 712 |
return true; |
| 713 |
} |
| 714 |
|
| 715 |
bool checkArguments(const CallExpr *CE) { |
| 716 |
for (const Expr *Arg : CE->arguments()) { |
| 717 |
if (Arg && !Visit(Arg)) |
| 718 |
return false; |
| 719 |
} |
| 720 |
return true; |
| 721 |
} |
| 722 |
|
| 723 |
bool VisitCXXConstructExpr(const CXXConstructExpr *CE) { |
| 724 |
for (const Expr *Arg : CE->arguments()) { |
| 725 |
if (Arg && !Visit(Arg)) |
| 726 |
return false; |
| 727 |
} |
| 728 |
|
| 729 |
// Recursively descend into the callee to confirm that it's trivial. |
| 730 |
return IsFunctionTrivial(CE->getConstructor()); |
| 731 |
} |
| 732 |
|
| 733 |
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E) { |
| 734 |
return IsFunctionTrivial(E->getConstructor()); |
| 735 |
} |
| 736 |
|
| 737 |
bool VisitCXXNewExpr(const CXXNewExpr *NE) { return VisitChildren(NE); } |
| 738 |
|
| 739 |
bool VisitImplicitCastExpr(const ImplicitCastExpr *ICE) { |
| 740 |
return Visit(ICE->getSubExpr()); |
| 741 |
} |
| 742 |
|
| 743 |
bool VisitExplicitCastExpr(const ExplicitCastExpr *ECE) { |
| 744 |
return Visit(ECE->getSubExpr()); |
| 745 |
} |
| 746 |
|
| 747 |
bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *VMT) { |
| 748 |
return Visit(VMT->getSubExpr()); |
| 749 |
} |
| 750 |
|
| 751 |
bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE) { |
| 752 |
if (auto *Temp = BTE->getTemporary()) { |
| 753 |
if (!TrivialFunctionAnalysis::isTrivialImpl(Temp->getDestructor(), Cache)) |
| 754 |
return false; |
| 755 |
} |
| 756 |
return Visit(BTE->getSubExpr()); |
| 757 |
} |
| 758 |
|
| 759 |
bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *AILE) { |
| 760 |
return Visit(AILE->getCommonExpr()) && Visit(AILE->getSubExpr()); |
| 761 |
} |
| 762 |
|
| 763 |
bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *AIIE) { |
| 764 |
return true; // The current array index in VisitArrayInitLoopExpr is always |
| 765 |
// trivial. |
| 766 |
} |
| 767 |
|
| 768 |
bool VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) { |
| 769 |
return Visit(OVE->getSourceExpr()); |
| 770 |
} |
| 771 |
|
| 772 |
bool VisitExprWithCleanups(const ExprWithCleanups *EWC) { |
| 773 |
return Visit(EWC->getSubExpr()); |
| 774 |
} |
| 775 |
|
| 776 |
bool VisitParenExpr(const ParenExpr *PE) { return Visit(PE->getSubExpr()); } |
| 777 |
|
| 778 |
bool VisitInitListExpr(const InitListExpr *ILE) { |
| 779 |
for (const Expr *Child : ILE->inits()) { |
| 780 |
if (Child && !Visit(Child)) |
| 781 |
return false; |
| 782 |
} |
| 783 |
return true; |
| 784 |
} |
| 785 |
|
| 786 |
bool VisitMemberExpr(const MemberExpr *ME) { |
| 787 |
// Field access is allowed but the base pointer may itself be non-trivial. |
| 788 |
return Visit(ME->getBase()); |
| 789 |
} |
| 790 |
|
| 791 |
bool VisitCXXThisExpr(const CXXThisExpr *CTE) { |
| 792 |
// The expression 'this' is always trivial, be it explicit or implicit. |
| 793 |
return true; |
| 794 |
} |
| 795 |
|
| 796 |
bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { |
| 797 |
// nullptr is trivial. |
| 798 |
return true; |
| 799 |
} |
| 800 |
|
| 801 |
bool VisitDeclRefExpr(const DeclRefExpr *DRE) { |
| 802 |
// The use of a variable is trivial. |
| 803 |
return true; |
| 804 |
} |
| 805 |
|
| 806 |
// Constant literal expressions are always trivial |
| 807 |
bool VisitIntegerLiteral(const IntegerLiteral *E) { return true; } |
| 808 |
bool VisitFloatingLiteral(const FloatingLiteral *E) { return true; } |
| 809 |
bool VisitFixedPointLiteral(const FixedPointLiteral *E) { return true; } |
| 810 |
bool VisitCharacterLiteral(const CharacterLiteral *E) { return true; } |
| 811 |
bool VisitStringLiteral(const StringLiteral *E) { return true; } |
| 812 |
bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return true; } |
| 813 |
|
| 814 |
bool VisitConstantExpr(const ConstantExpr *CE) { |
| 815 |
// Constant expressions are trivial. |
| 816 |
return true; |
| 817 |
} |
| 818 |
|
| 819 |
bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *IVIE) { |
| 820 |
// An implicit value initialization is trvial. |
| 821 |
return true; |
| 822 |
} |
| 823 |
|
| 824 |
private: |
| 825 |
CacheTy &Cache; |
| 826 |
CacheTy RecursiveFn; |
| 827 |
}; |
| 828 |
|
| 829 |
bool TrivialFunctionAnalysis::isTrivialImpl( |
| 830 |
const Decl *D, TrivialFunctionAnalysis::CacheTy &Cache) { |
| 831 |
TrivialFunctionAnalysisVisitor V(Cache); |
| 832 |
return V.IsFunctionTrivial(D); |
| 833 |
} |
| 834 |
|
| 835 |
bool TrivialFunctionAnalysis::isTrivialImpl( |
| 836 |
const Stmt *S, TrivialFunctionAnalysis::CacheTy &Cache) { |
| 837 |
TrivialFunctionAnalysisVisitor V(Cache); |
| 838 |
return V.IsStatementTrivial(S); |
| 839 |
} |
| 840 |
|
| 841 |
} // namespace clang |