1 //===-- UncheckedOptionalAccessModel.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 // This file defines a dataflow analysis that detects unsafe uses of optional 10 // values. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/Stmt.h" 20 #include "clang/ASTMatchers/ASTMatchers.h" 21 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h" 22 #include "clang/Analysis/FlowSensitive/MatchSwitch.h" 23 #include "clang/Analysis/FlowSensitive/SourceLocationsLattice.h" 24 #include "clang/Analysis/FlowSensitive/Value.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/Support/Casting.h" 27 #include <cassert> 28 #include <memory> 29 #include <utility> 30 31 namespace clang { 32 namespace dataflow { 33 namespace { 34 35 using namespace ::clang::ast_matchers; 36 using LatticeTransferState = TransferState<SourceLocationsLattice>; 37 38 DeclarationMatcher optionalClass() { 39 return classTemplateSpecializationDecl( 40 anyOf(hasName("std::optional"), hasName("std::__optional_storage_base"), 41 hasName("__optional_destruct_base"), hasName("absl::optional"), 42 hasName("base::Optional")), 43 hasTemplateArgument(0, refersToType(type().bind("T")))); 44 } 45 46 auto optionalOrAliasType() { 47 return hasUnqualifiedDesugaredType( 48 recordType(hasDeclaration(optionalClass()))); 49 } 50 51 /// Matches any of the spellings of the optional types and sugar, aliases, etc. 52 auto hasOptionalType() { return hasType(optionalOrAliasType()); } 53 54 auto isOptionalMemberCallWithName( 55 llvm::StringRef MemberName, 56 llvm::Optional<StatementMatcher> Ignorable = llvm::None) { 57 auto Exception = unless(Ignorable ? expr(anyOf(*Ignorable, cxxThisExpr())) 58 : cxxThisExpr()); 59 return cxxMemberCallExpr( 60 on(expr(Exception)), 61 callee(cxxMethodDecl(hasName(MemberName), ofClass(optionalClass())))); 62 } 63 64 auto isOptionalOperatorCallWithName( 65 llvm::StringRef operator_name, 66 llvm::Optional<StatementMatcher> Ignorable = llvm::None) { 67 return cxxOperatorCallExpr( 68 hasOverloadedOperatorName(operator_name), 69 callee(cxxMethodDecl(ofClass(optionalClass()))), 70 Ignorable ? callExpr(unless(hasArgument(0, *Ignorable))) : callExpr()); 71 } 72 73 auto isMakeOptionalCall() { 74 return callExpr( 75 callee(functionDecl(hasAnyName( 76 "std::make_optional", "base::make_optional", "absl::make_optional"))), 77 hasOptionalType()); 78 } 79 80 auto hasNulloptType() { 81 return hasType(namedDecl( 82 hasAnyName("std::nullopt_t", "absl::nullopt_t", "base::nullopt_t"))); 83 } 84 85 auto inPlaceClass() { 86 return recordDecl( 87 hasAnyName("std::in_place_t", "absl::in_place_t", "base::in_place_t")); 88 } 89 90 auto isOptionalNulloptConstructor() { 91 return cxxConstructExpr(hasOptionalType(), argumentCountIs(1), 92 hasArgument(0, hasNulloptType())); 93 } 94 95 auto isOptionalInPlaceConstructor() { 96 return cxxConstructExpr(hasOptionalType(), 97 hasArgument(0, hasType(inPlaceClass()))); 98 } 99 100 auto isOptionalValueOrConversionConstructor() { 101 return cxxConstructExpr( 102 hasOptionalType(), 103 unless(hasDeclaration( 104 cxxConstructorDecl(anyOf(isCopyConstructor(), isMoveConstructor())))), 105 argumentCountIs(1), hasArgument(0, unless(hasNulloptType()))); 106 } 107 108 auto isOptionalValueOrConversionAssignment() { 109 return cxxOperatorCallExpr( 110 hasOverloadedOperatorName("="), 111 callee(cxxMethodDecl(ofClass(optionalClass()))), 112 unless(hasDeclaration(cxxMethodDecl( 113 anyOf(isCopyAssignmentOperator(), isMoveAssignmentOperator())))), 114 argumentCountIs(2), hasArgument(1, unless(hasNulloptType()))); 115 } 116 117 auto isOptionalNulloptAssignment() { 118 return cxxOperatorCallExpr(hasOverloadedOperatorName("="), 119 callee(cxxMethodDecl(ofClass(optionalClass()))), 120 argumentCountIs(2), 121 hasArgument(1, hasNulloptType())); 122 } 123 124 auto isStdSwapCall() { 125 return callExpr(callee(functionDecl(hasName("std::swap"))), 126 argumentCountIs(2), hasArgument(0, hasOptionalType()), 127 hasArgument(1, hasOptionalType())); 128 } 129 130 constexpr llvm::StringLiteral ValueOrCallID = "ValueOrCall"; 131 132 auto isValueOrStringEmptyCall() { 133 // `opt.value_or("").empty()` 134 return cxxMemberCallExpr( 135 callee(cxxMethodDecl(hasName("empty"))), 136 onImplicitObjectArgument(ignoringImplicit( 137 cxxMemberCallExpr(on(expr(unless(cxxThisExpr()))), 138 callee(cxxMethodDecl(hasName("value_or"), 139 ofClass(optionalClass()))), 140 hasArgument(0, stringLiteral(hasSize(0)))) 141 .bind(ValueOrCallID)))); 142 } 143 144 auto isValueOrNotEqX() { 145 auto ComparesToSame = [](ast_matchers::internal::Matcher<Stmt> Arg) { 146 return hasOperands( 147 ignoringImplicit( 148 cxxMemberCallExpr(on(expr(unless(cxxThisExpr()))), 149 callee(cxxMethodDecl(hasName("value_or"), 150 ofClass(optionalClass()))), 151 hasArgument(0, Arg)) 152 .bind(ValueOrCallID)), 153 ignoringImplicit(Arg)); 154 }; 155 156 // `opt.value_or(X) != X`, for X is `nullptr`, `""`, or `0`. Ideally, we'd 157 // support this pattern for any expression, but the AST does not have a 158 // generic expression comparison facility, so we specialize to common cases 159 // seen in practice. FIXME: define a matcher that compares values across 160 // nodes, which would let us generalize this to any `X`. 161 return binaryOperation(hasOperatorName("!="), 162 anyOf(ComparesToSame(cxxNullPtrLiteralExpr()), 163 ComparesToSame(stringLiteral(hasSize(0))), 164 ComparesToSame(integerLiteral(equals(0))))); 165 } 166 167 auto isCallReturningOptional() { 168 return callExpr(callee(functionDecl(returns(anyOf( 169 optionalOrAliasType(), referenceType(pointee(optionalOrAliasType()))))))); 170 } 171 172 /// Creates a symbolic value for an `optional` value using `HasValueVal` as the 173 /// symbolic value of its "has_value" property. 174 StructValue &createOptionalValue(Environment &Env, BoolValue &HasValueVal) { 175 auto OptionalVal = std::make_unique<StructValue>(); 176 OptionalVal->setProperty("has_value", HasValueVal); 177 return Env.takeOwnership(std::move(OptionalVal)); 178 } 179 180 /// Returns the symbolic value that represents the "has_value" property of the 181 /// optional value `OptionalVal`. Returns null if `OptionalVal` is null. 182 BoolValue *getHasValue(Environment &Env, Value *OptionalVal) { 183 if (OptionalVal != nullptr) { 184 auto *HasValueVal = 185 cast_or_null<BoolValue>(OptionalVal->getProperty("has_value")); 186 if (HasValueVal == nullptr) { 187 HasValueVal = &Env.makeAtomicBoolValue(); 188 OptionalVal->setProperty("has_value", *HasValueVal); 189 } 190 return HasValueVal; 191 } 192 return nullptr; 193 } 194 195 /// If `Type` is a reference type, returns the type of its pointee. Otherwise, 196 /// returns `Type` itself. 197 QualType stripReference(QualType Type) { 198 return Type->isReferenceType() ? Type->getPointeeType() : Type; 199 } 200 201 /// Returns true if and only if `Type` is an optional type. 202 bool IsOptionalType(QualType Type) { 203 if (!Type->isRecordType()) 204 return false; 205 // FIXME: Optimize this by avoiding the `getQualifiedNameAsString` call. 206 auto TypeName = Type->getAsCXXRecordDecl()->getQualifiedNameAsString(); 207 return TypeName == "std::optional" || TypeName == "absl::optional" || 208 TypeName == "base::Optional"; 209 } 210 211 /// Returns the number of optional wrappers in `Type`. 212 /// 213 /// For example, if `Type` is `optional<optional<int>>`, the result of this 214 /// function will be 2. 215 int countOptionalWrappers(const ASTContext &ASTCtx, QualType Type) { 216 if (!IsOptionalType(Type)) 217 return 0; 218 return 1 + countOptionalWrappers( 219 ASTCtx, 220 cast<ClassTemplateSpecializationDecl>(Type->getAsRecordDecl()) 221 ->getTemplateArgs() 222 .get(0) 223 .getAsType() 224 .getDesugaredType(ASTCtx)); 225 } 226 227 /// Tries to initialize the `optional`'s value (that is, contents), and return 228 /// its location. Returns nullptr if the value can't be represented. 229 StorageLocation *maybeInitializeOptionalValueMember(QualType Q, 230 Value &OptionalVal, 231 Environment &Env) { 232 // The "value" property represents a synthetic field. As such, it needs 233 // `StorageLocation`, like normal fields (and other variables). So, we model 234 // it with a `ReferenceValue`, since that includes a storage location. Once 235 // the property is set, it will be shared by all environments that access the 236 // `Value` representing the optional (here, `OptionalVal`). 237 if (auto *ValueProp = OptionalVal.getProperty("value")) { 238 auto *ValueRef = clang::cast<ReferenceValue>(ValueProp); 239 auto &ValueLoc = ValueRef->getPointeeLoc(); 240 if (Env.getValue(ValueLoc) == nullptr) { 241 // The property was previously set, but the value has been lost. This can 242 // happen, for example, because of an environment merge (where the two 243 // environments mapped the property to different values, which resulted in 244 // them both being discarded), or when two blocks in the CFG, with neither 245 // a dominator of the other, visit the same optional value, or even when a 246 // block is revisited during testing to collect per-statement state. 247 // FIXME: This situation means that the optional contents are not shared 248 // between branches and the like. Practically, this lack of sharing 249 // reduces the precision of the model when the contents are relevant to 250 // the check, like another optional or a boolean that influences control 251 // flow. 252 auto *ValueVal = Env.createValue(ValueLoc.getType()); 253 if (ValueVal == nullptr) 254 return nullptr; 255 Env.setValue(ValueLoc, *ValueVal); 256 } 257 return &ValueLoc; 258 } 259 260 auto Ty = stripReference(Q); 261 auto *ValueVal = Env.createValue(Ty); 262 if (ValueVal == nullptr) 263 return nullptr; 264 auto &ValueLoc = Env.createStorageLocation(Ty); 265 Env.setValue(ValueLoc, *ValueVal); 266 auto ValueRef = std::make_unique<ReferenceValue>(ValueLoc); 267 OptionalVal.setProperty("value", Env.takeOwnership(std::move(ValueRef))); 268 return &ValueLoc; 269 } 270 271 void initializeOptionalReference(const Expr *OptionalExpr, 272 const MatchFinder::MatchResult &, 273 LatticeTransferState &State) { 274 if (auto *OptionalVal = 275 State.Env.getValue(*OptionalExpr, SkipPast::Reference)) { 276 if (OptionalVal->getProperty("has_value") == nullptr) { 277 OptionalVal->setProperty("has_value", State.Env.makeAtomicBoolValue()); 278 } 279 } 280 } 281 282 void transferUnwrapCall(const Expr *UnwrapExpr, const Expr *ObjectExpr, 283 LatticeTransferState &State) { 284 if (auto *OptionalVal = 285 State.Env.getValue(*ObjectExpr, SkipPast::ReferenceThenPointer)) { 286 if (State.Env.getStorageLocation(*UnwrapExpr, SkipPast::None) == nullptr) 287 if (auto *Loc = maybeInitializeOptionalValueMember( 288 UnwrapExpr->getType(), *OptionalVal, State.Env)) 289 State.Env.setStorageLocation(*UnwrapExpr, *Loc); 290 291 auto *Prop = OptionalVal->getProperty("has_value"); 292 if (auto *HasValueVal = cast_or_null<BoolValue>(Prop)) { 293 if (State.Env.flowConditionImplies(*HasValueVal)) 294 return; 295 } 296 } 297 298 // Record that this unwrap is *not* provably safe. 299 // FIXME: include either the name of the optional (if applicable) or a source 300 // range of the access for easier interpretation of the result. 301 State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc()); 302 } 303 304 void transferMakeOptionalCall(const CallExpr *E, 305 const MatchFinder::MatchResult &, 306 LatticeTransferState &State) { 307 auto &Loc = State.Env.createStorageLocation(*E); 308 State.Env.setStorageLocation(*E, Loc); 309 State.Env.setValue( 310 Loc, createOptionalValue(State.Env, State.Env.getBoolLiteralValue(true))); 311 } 312 313 void transferOptionalHasValueCall(const CXXMemberCallExpr *CallExpr, 314 const MatchFinder::MatchResult &, 315 LatticeTransferState &State) { 316 if (auto *HasValueVal = getHasValue( 317 State.Env, State.Env.getValue(*CallExpr->getImplicitObjectArgument(), 318 SkipPast::ReferenceThenPointer))) { 319 auto &CallExprLoc = State.Env.createStorageLocation(*CallExpr); 320 State.Env.setValue(CallExprLoc, *HasValueVal); 321 State.Env.setStorageLocation(*CallExpr, CallExprLoc); 322 } 323 } 324 325 /// `ModelPred` builds a logical formula relating the predicate in 326 /// `ValueOrPredExpr` to the optional's `has_value` property. 327 void transferValueOrImpl(const clang::Expr *ValueOrPredExpr, 328 const MatchFinder::MatchResult &Result, 329 LatticeTransferState &State, 330 BoolValue &(*ModelPred)(Environment &Env, 331 BoolValue &ExprVal, 332 BoolValue &HasValueVal)) { 333 auto &Env = State.Env; 334 335 const auto *ObjectArgumentExpr = 336 Result.Nodes.getNodeAs<clang::CXXMemberCallExpr>(ValueOrCallID) 337 ->getImplicitObjectArgument(); 338 339 auto *HasValueVal = getHasValue( 340 State.Env, 341 State.Env.getValue(*ObjectArgumentExpr, SkipPast::ReferenceThenPointer)); 342 if (HasValueVal == nullptr) 343 return; 344 345 auto *ExprValue = cast_or_null<BoolValue>( 346 State.Env.getValue(*ValueOrPredExpr, SkipPast::None)); 347 if (ExprValue == nullptr) { 348 auto &ExprLoc = State.Env.createStorageLocation(*ValueOrPredExpr); 349 ExprValue = &State.Env.makeAtomicBoolValue(); 350 State.Env.setValue(ExprLoc, *ExprValue); 351 State.Env.setStorageLocation(*ValueOrPredExpr, ExprLoc); 352 } 353 354 Env.addToFlowCondition(ModelPred(Env, *ExprValue, *HasValueVal)); 355 } 356 357 void transferValueOrStringEmptyCall(const clang::Expr *ComparisonExpr, 358 const MatchFinder::MatchResult &Result, 359 LatticeTransferState &State) { 360 return transferValueOrImpl(ComparisonExpr, Result, State, 361 [](Environment &Env, BoolValue &ExprVal, 362 BoolValue &HasValueVal) -> BoolValue & { 363 // If the result is *not* empty, then we know the 364 // optional must have been holding a value. If 365 // `ExprVal` is true, though, we don't learn 366 // anything definite about `has_value`, so we 367 // don't add any corresponding implications to 368 // the flow condition. 369 return Env.makeImplication(Env.makeNot(ExprVal), 370 HasValueVal); 371 }); 372 } 373 374 void transferValueOrNotEqX(const Expr *ComparisonExpr, 375 const MatchFinder::MatchResult &Result, 376 LatticeTransferState &State) { 377 transferValueOrImpl(ComparisonExpr, Result, State, 378 [](Environment &Env, BoolValue &ExprVal, 379 BoolValue &HasValueVal) -> BoolValue & { 380 // We know that if `(opt.value_or(X) != X)` then 381 // `opt.hasValue()`, even without knowing further 382 // details about the contents of `opt`. 383 return Env.makeImplication(ExprVal, HasValueVal); 384 }); 385 } 386 387 void transferCallReturningOptional(const CallExpr *E, 388 const MatchFinder::MatchResult &Result, 389 LatticeTransferState &State) { 390 if (State.Env.getStorageLocation(*E, SkipPast::None) != nullptr) 391 return; 392 393 auto &Loc = State.Env.createStorageLocation(*E); 394 State.Env.setStorageLocation(*E, Loc); 395 State.Env.setValue( 396 Loc, createOptionalValue(State.Env, State.Env.makeAtomicBoolValue())); 397 } 398 399 void assignOptionalValue(const Expr &E, LatticeTransferState &State, 400 BoolValue &HasValueVal) { 401 if (auto *OptionalLoc = 402 State.Env.getStorageLocation(E, SkipPast::ReferenceThenPointer)) { 403 State.Env.setValue(*OptionalLoc, 404 createOptionalValue(State.Env, HasValueVal)); 405 } 406 } 407 408 /// Returns a symbolic value for the "has_value" property of an `optional<T>` 409 /// value that is constructed/assigned from a value of type `U` or `optional<U>` 410 /// where `T` is constructible from `U`. 411 BoolValue & 412 getValueOrConversionHasValue(const FunctionDecl &F, const Expr &E, 413 const MatchFinder::MatchResult &MatchRes, 414 LatticeTransferState &State) { 415 assert(F.getTemplateSpecializationArgs()->size() > 0); 416 417 const int TemplateParamOptionalWrappersCount = countOptionalWrappers( 418 *MatchRes.Context, 419 stripReference(F.getTemplateSpecializationArgs()->get(0).getAsType())); 420 const int ArgTypeOptionalWrappersCount = 421 countOptionalWrappers(*MatchRes.Context, stripReference(E.getType())); 422 423 // Check if this is a constructor/assignment call for `optional<T>` with 424 // argument of type `U` such that `T` is constructible from `U`. 425 if (TemplateParamOptionalWrappersCount == ArgTypeOptionalWrappersCount) 426 return State.Env.getBoolLiteralValue(true); 427 428 // This is a constructor/assignment call for `optional<T>` with argument of 429 // type `optional<U>` such that `T` is constructible from `U`. 430 if (auto *HasValueVal = 431 getHasValue(State.Env, State.Env.getValue(E, SkipPast::Reference))) 432 return *HasValueVal; 433 return State.Env.makeAtomicBoolValue(); 434 } 435 436 void transferValueOrConversionConstructor( 437 const CXXConstructExpr *E, const MatchFinder::MatchResult &MatchRes, 438 LatticeTransferState &State) { 439 assert(E->getNumArgs() > 0); 440 441 assignOptionalValue(*E, State, 442 getValueOrConversionHasValue(*E->getConstructor(), 443 *E->getArg(0), MatchRes, 444 State)); 445 } 446 447 void transferAssignment(const CXXOperatorCallExpr *E, BoolValue &HasValueVal, 448 LatticeTransferState &State) { 449 assert(E->getNumArgs() > 0); 450 451 auto *OptionalLoc = 452 State.Env.getStorageLocation(*E->getArg(0), SkipPast::Reference); 453 assert(OptionalLoc != nullptr); 454 455 State.Env.setValue(*OptionalLoc, createOptionalValue(State.Env, HasValueVal)); 456 457 // Assign a storage location for the whole expression. 458 State.Env.setStorageLocation(*E, *OptionalLoc); 459 } 460 461 void transferValueOrConversionAssignment( 462 const CXXOperatorCallExpr *E, const MatchFinder::MatchResult &MatchRes, 463 LatticeTransferState &State) { 464 assert(E->getNumArgs() > 1); 465 transferAssignment(E, 466 getValueOrConversionHasValue( 467 *E->getDirectCallee(), *E->getArg(1), MatchRes, State), 468 State); 469 } 470 471 void transferNulloptAssignment(const CXXOperatorCallExpr *E, 472 const MatchFinder::MatchResult &, 473 LatticeTransferState &State) { 474 transferAssignment(E, State.Env.getBoolLiteralValue(false), State); 475 } 476 477 void transferSwap(const StorageLocation &OptionalLoc1, 478 const StorageLocation &OptionalLoc2, 479 LatticeTransferState &State) { 480 auto *OptionalVal1 = State.Env.getValue(OptionalLoc1); 481 assert(OptionalVal1 != nullptr); 482 483 auto *OptionalVal2 = State.Env.getValue(OptionalLoc2); 484 assert(OptionalVal2 != nullptr); 485 486 State.Env.setValue(OptionalLoc1, *OptionalVal2); 487 State.Env.setValue(OptionalLoc2, *OptionalVal1); 488 } 489 490 void transferSwapCall(const CXXMemberCallExpr *E, 491 const MatchFinder::MatchResult &, 492 LatticeTransferState &State) { 493 assert(E->getNumArgs() == 1); 494 495 auto *OptionalLoc1 = State.Env.getStorageLocation( 496 *E->getImplicitObjectArgument(), SkipPast::ReferenceThenPointer); 497 assert(OptionalLoc1 != nullptr); 498 499 auto *OptionalLoc2 = 500 State.Env.getStorageLocation(*E->getArg(0), SkipPast::Reference); 501 assert(OptionalLoc2 != nullptr); 502 503 transferSwap(*OptionalLoc1, *OptionalLoc2, State); 504 } 505 506 void transferStdSwapCall(const CallExpr *E, const MatchFinder::MatchResult &, 507 LatticeTransferState &State) { 508 assert(E->getNumArgs() == 2); 509 510 auto *OptionalLoc1 = 511 State.Env.getStorageLocation(*E->getArg(0), SkipPast::Reference); 512 assert(OptionalLoc1 != nullptr); 513 514 auto *OptionalLoc2 = 515 State.Env.getStorageLocation(*E->getArg(1), SkipPast::Reference); 516 assert(OptionalLoc2 != nullptr); 517 518 transferSwap(*OptionalLoc1, *OptionalLoc2, State); 519 } 520 521 llvm::Optional<StatementMatcher> 522 ignorableOptional(const UncheckedOptionalAccessModelOptions &Options) { 523 if (Options.IgnoreSmartPointerDereference) 524 return memberExpr(hasObjectExpression(ignoringParenImpCasts( 525 cxxOperatorCallExpr(anyOf(hasOverloadedOperatorName("->"), 526 hasOverloadedOperatorName("*")), 527 unless(hasArgument(0, expr(hasOptionalType()))))))); 528 return llvm::None; 529 } 530 531 auto buildTransferMatchSwitch( 532 const UncheckedOptionalAccessModelOptions &Options) { 533 // FIXME: Evaluate the efficiency of matchers. If using matchers results in a 534 // lot of duplicated work (e.g. string comparisons), consider providing APIs 535 // that avoid it through memoization. 536 auto IgnorableOptional = ignorableOptional(Options); 537 return MatchSwitchBuilder<LatticeTransferState>() 538 // Attach a symbolic "has_value" state to optional values that we see for 539 // the first time. 540 .CaseOf<Expr>( 541 expr(anyOf(declRefExpr(), memberExpr()), hasOptionalType()), 542 initializeOptionalReference) 543 544 // make_optional 545 .CaseOf<CallExpr>(isMakeOptionalCall(), transferMakeOptionalCall) 546 547 // optional::optional 548 .CaseOf<CXXConstructExpr>( 549 isOptionalInPlaceConstructor(), 550 [](const CXXConstructExpr *E, const MatchFinder::MatchResult &, 551 LatticeTransferState &State) { 552 assignOptionalValue(*E, State, State.Env.getBoolLiteralValue(true)); 553 }) 554 .CaseOf<CXXConstructExpr>( 555 isOptionalNulloptConstructor(), 556 [](const CXXConstructExpr *E, const MatchFinder::MatchResult &, 557 LatticeTransferState &State) { 558 assignOptionalValue(*E, State, 559 State.Env.getBoolLiteralValue(false)); 560 }) 561 .CaseOf<CXXConstructExpr>(isOptionalValueOrConversionConstructor(), 562 transferValueOrConversionConstructor) 563 564 // optional::operator= 565 .CaseOf<CXXOperatorCallExpr>(isOptionalValueOrConversionAssignment(), 566 transferValueOrConversionAssignment) 567 .CaseOf<CXXOperatorCallExpr>(isOptionalNulloptAssignment(), 568 transferNulloptAssignment) 569 570 // optional::value 571 .CaseOf<CXXMemberCallExpr>( 572 isOptionalMemberCallWithName("value", IgnorableOptional), 573 [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, 574 LatticeTransferState &State) { 575 transferUnwrapCall(E, E->getImplicitObjectArgument(), State); 576 }) 577 578 // optional::operator*, optional::operator-> 579 .CaseOf<CallExpr>( 580 expr(anyOf(isOptionalOperatorCallWithName("*", IgnorableOptional), 581 isOptionalOperatorCallWithName("->", IgnorableOptional))), 582 [](const CallExpr *E, const MatchFinder::MatchResult &, 583 LatticeTransferState &State) { 584 transferUnwrapCall(E, E->getArg(0), State); 585 }) 586 587 // optional::has_value 588 .CaseOf<CXXMemberCallExpr>(isOptionalMemberCallWithName("has_value"), 589 transferOptionalHasValueCall) 590 591 // optional::operator bool 592 .CaseOf<CXXMemberCallExpr>(isOptionalMemberCallWithName("operator bool"), 593 transferOptionalHasValueCall) 594 595 // optional::emplace 596 .CaseOf<CXXMemberCallExpr>( 597 isOptionalMemberCallWithName("emplace"), 598 [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, 599 LatticeTransferState &State) { 600 assignOptionalValue(*E->getImplicitObjectArgument(), State, 601 State.Env.getBoolLiteralValue(true)); 602 }) 603 604 // optional::reset 605 .CaseOf<CXXMemberCallExpr>( 606 isOptionalMemberCallWithName("reset"), 607 [](const CXXMemberCallExpr *E, const MatchFinder::MatchResult &, 608 LatticeTransferState &State) { 609 assignOptionalValue(*E->getImplicitObjectArgument(), State, 610 State.Env.getBoolLiteralValue(false)); 611 }) 612 613 // optional::swap 614 .CaseOf<CXXMemberCallExpr>(isOptionalMemberCallWithName("swap"), 615 transferSwapCall) 616 617 // std::swap 618 .CaseOf<CallExpr>(isStdSwapCall(), transferStdSwapCall) 619 620 // opt.value_or("").empty() 621 .CaseOf<Expr>(isValueOrStringEmptyCall(), transferValueOrStringEmptyCall) 622 623 // opt.value_or(X) != X 624 .CaseOf<Expr>(isValueOrNotEqX(), transferValueOrNotEqX) 625 626 // returns optional 627 .CaseOf<CallExpr>(isCallReturningOptional(), 628 transferCallReturningOptional) 629 630 .Build(); 631 } 632 633 } // namespace 634 635 ast_matchers::DeclarationMatcher 636 UncheckedOptionalAccessModel::optionalClassDecl() { 637 return optionalClass(); 638 } 639 640 UncheckedOptionalAccessModel::UncheckedOptionalAccessModel( 641 ASTContext &Ctx, UncheckedOptionalAccessModelOptions Options) 642 : DataflowAnalysis<UncheckedOptionalAccessModel, SourceLocationsLattice>( 643 Ctx), 644 TransferMatchSwitch(buildTransferMatchSwitch(Options)) {} 645 646 void UncheckedOptionalAccessModel::transfer(const Stmt *S, 647 SourceLocationsLattice &L, 648 Environment &Env) { 649 LatticeTransferState State(L, Env); 650 TransferMatchSwitch(*S, getASTContext(), State); 651 } 652 653 } // namespace dataflow 654 } // namespace clang 655