| 1 | //===--- CheckExprLifetime.cpp --------------------------------------------===// |
| 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 "CheckExprLifetime.h" |
| 10 | #include "clang/AST/Decl.h" |
| 11 | #include "clang/AST/Expr.h" |
| 12 | #include "clang/AST/Type.h" |
| 13 | #include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h" |
| 14 | #include "clang/Basic/DiagnosticSema.h" |
| 15 | #include "clang/Sema/Initialization.h" |
| 16 | #include "clang/Sema/Sema.h" |
| 17 | #include "llvm/ADT/PointerIntPair.h" |
| 18 | |
| 19 | namespace clang::sema { |
| 20 | using lifetimes::isGslOwnerType; |
| 21 | using lifetimes::isGslPointerType; |
| 22 | |
| 23 | namespace { |
| 24 | enum LifetimeKind { |
| 25 | /// The lifetime of a temporary bound to this entity ends at the end of the |
| 26 | /// full-expression, and that's (probably) fine. |
| 27 | LK_FullExpression, |
| 28 | |
| 29 | /// The lifetime of a temporary bound to this entity is extended to the |
| 30 | /// lifeitme of the entity itself. |
| 31 | LK_Extended, |
| 32 | |
| 33 | /// The lifetime of a temporary bound to this entity probably ends too soon, |
| 34 | /// because the entity is allocated in a new-expression. |
| 35 | LK_New, |
| 36 | |
| 37 | /// The lifetime of a temporary bound to this entity ends too soon, because |
| 38 | /// the entity is a return object. |
| 39 | LK_Return, |
| 40 | |
| 41 | /// The lifetime of a temporary bound to this entity ends too soon, because |
| 42 | /// the entity passed to a musttail function call. |
| 43 | LK_MustTail, |
| 44 | |
| 45 | /// The lifetime of a temporary bound to this entity ends too soon, because |
| 46 | /// the entity is the result of a statement expression. |
| 47 | LK_StmtExprResult, |
| 48 | |
| 49 | /// This is a mem-initializer: if it would extend a temporary (other than via |
| 50 | /// a default member initializer), the program is ill-formed. |
| 51 | LK_MemInitializer, |
| 52 | |
| 53 | /// The lifetime of a temporary bound to this entity may end too soon, |
| 54 | /// because the entity is a pointer and we assign the address of a temporary |
| 55 | /// object to it. |
| 56 | LK_Assignment, |
| 57 | |
| 58 | /// The lifetime of a temporary bound to this entity may end too soon, |
| 59 | /// because the entity may capture the reference to a temporary object. |
| 60 | LK_LifetimeCapture, |
| 61 | }; |
| 62 | using LifetimeResult = |
| 63 | llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>; |
| 64 | } // namespace |
| 65 | |
| 66 | /// Determine the declaration which an initialized entity ultimately refers to, |
| 67 | /// for the purpose of lifetime-extending a temporary bound to a reference in |
| 68 | /// the initialization of \p Entity. |
| 69 | static LifetimeResult |
| 70 | getEntityLifetime(const InitializedEntity *Entity, |
| 71 | const InitializedEntity *InitField = nullptr) { |
| 72 | // C++11 [class.temporary]p5: |
| 73 | switch (Entity->getKind()) { |
| 74 | case InitializedEntity::EK_Variable: |
| 75 | // The temporary [...] persists for the lifetime of the reference |
| 76 | return {Entity, LK_Extended}; |
| 77 | |
| 78 | case InitializedEntity::EK_Member: |
| 79 | // For subobjects, we look at the complete object. |
| 80 | if (Entity->getParent()) |
| 81 | return getEntityLifetime(Entity: Entity->getParent(), InitField: Entity); |
| 82 | |
| 83 | // except: |
| 84 | // C++17 [class.base.init]p8: |
| 85 | // A temporary expression bound to a reference member in a |
| 86 | // mem-initializer is ill-formed. |
| 87 | // C++17 [class.base.init]p11: |
| 88 | // A temporary expression bound to a reference member from a |
| 89 | // default member initializer is ill-formed. |
| 90 | // |
| 91 | // The context of p11 and its example suggest that it's only the use of a |
| 92 | // default member initializer from a constructor that makes the program |
| 93 | // ill-formed, not its mere existence, and that it can even be used by |
| 94 | // aggregate initialization. |
| 95 | return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended |
| 96 | : LK_MemInitializer}; |
| 97 | |
| 98 | case InitializedEntity::EK_Binding: |
| 99 | // Per [dcl.decomp]p3, the binding is treated as a variable of reference |
| 100 | // type. |
| 101 | return {Entity, LK_Extended}; |
| 102 | |
| 103 | case InitializedEntity::EK_Parameter: |
| 104 | case InitializedEntity::EK_Parameter_CF_Audited: |
| 105 | // -- A temporary bound to a reference parameter in a function call |
| 106 | // persists until the completion of the full-expression containing |
| 107 | // the call. |
| 108 | return {nullptr, LK_FullExpression}; |
| 109 | |
| 110 | case InitializedEntity::EK_TemplateParameter: |
| 111 | // FIXME: This will always be ill-formed; should we eagerly diagnose it |
| 112 | // here? |
| 113 | return {nullptr, LK_FullExpression}; |
| 114 | |
| 115 | case InitializedEntity::EK_Result: |
| 116 | // -- The lifetime of a temporary bound to the returned value in a |
| 117 | // function return statement is not extended; the temporary is |
| 118 | // destroyed at the end of the full-expression in the return statement. |
| 119 | return {nullptr, LK_Return}; |
| 120 | |
| 121 | case InitializedEntity::EK_StmtExprResult: |
| 122 | // FIXME: Should we lifetime-extend through the result of a statement |
| 123 | // expression? |
| 124 | return {nullptr, LK_StmtExprResult}; |
| 125 | |
| 126 | case InitializedEntity::EK_New: |
| 127 | // -- A temporary bound to a reference in a new-initializer persists |
| 128 | // until the completion of the full-expression containing the |
| 129 | // new-initializer. |
| 130 | return {nullptr, LK_New}; |
| 131 | |
| 132 | case InitializedEntity::EK_Temporary: |
| 133 | case InitializedEntity::EK_CompoundLiteralInit: |
| 134 | case InitializedEntity::EK_RelatedResult: |
| 135 | // We don't yet know the storage duration of the surrounding temporary. |
| 136 | // Assume it's got full-expression duration for now, it will patch up our |
| 137 | // storage duration if that's not correct. |
| 138 | return {nullptr, LK_FullExpression}; |
| 139 | |
| 140 | case InitializedEntity::EK_ArrayElement: |
| 141 | // For subobjects, we look at the complete object. |
| 142 | return getEntityLifetime(Entity: Entity->getParent(), InitField); |
| 143 | |
| 144 | case InitializedEntity::EK_Base: |
| 145 | // For subobjects, we look at the complete object. |
| 146 | if (Entity->getParent()) |
| 147 | return getEntityLifetime(Entity: Entity->getParent(), InitField); |
| 148 | return {InitField, LK_MemInitializer}; |
| 149 | |
| 150 | case InitializedEntity::EK_Delegating: |
| 151 | // We can reach this case for aggregate initialization in a constructor: |
| 152 | // struct A { int &&r; }; |
| 153 | // struct B : A { B() : A{0} {} }; |
| 154 | // In this case, use the outermost field decl as the context. |
| 155 | return {InitField, LK_MemInitializer}; |
| 156 | |
| 157 | case InitializedEntity::EK_BlockElement: |
| 158 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
| 159 | case InitializedEntity::EK_LambdaCapture: |
| 160 | case InitializedEntity::EK_VectorElement: |
| 161 | case InitializedEntity::EK_MatrixElement: |
| 162 | case InitializedEntity::EK_ComplexElement: |
| 163 | return {nullptr, LK_FullExpression}; |
| 164 | |
| 165 | case InitializedEntity::EK_Exception: |
| 166 | // FIXME: Can we diagnose lifetime problems with exceptions? |
| 167 | return {nullptr, LK_FullExpression}; |
| 168 | |
| 169 | case InitializedEntity::EK_ParenAggInitMember: |
| 170 | // -- A temporary object bound to a reference element of an aggregate of |
| 171 | // class type initialized from a parenthesized expression-list |
| 172 | // [dcl.init, 9.3] persists until the completion of the full-expression |
| 173 | // containing the expression-list. |
| 174 | return {nullptr, LK_FullExpression}; |
| 175 | } |
| 176 | |
| 177 | llvm_unreachable("unknown entity kind" ); |
| 178 | } |
| 179 | |
| 180 | namespace { |
| 181 | enum ReferenceKind { |
| 182 | /// Lifetime would be extended by a reference binding to a temporary. |
| 183 | RK_ReferenceBinding, |
| 184 | /// Lifetime would be extended by a std::initializer_list object binding to |
| 185 | /// its backing array. |
| 186 | RK_StdInitializerList, |
| 187 | }; |
| 188 | |
| 189 | /// A temporary or local variable. This will be one of: |
| 190 | /// * A MaterializeTemporaryExpr. |
| 191 | /// * A DeclRefExpr whose declaration is a local. |
| 192 | /// * An AddrLabelExpr. |
| 193 | /// * A BlockExpr for a block with captures. |
| 194 | using Local = Expr *; |
| 195 | |
| 196 | /// Expressions we stepped over when looking for the local state. Any steps |
| 197 | /// that would inhibit lifetime extension or take us out of subexpressions of |
| 198 | /// the initializer are included. |
| 199 | struct IndirectLocalPathEntry { |
| 200 | enum EntryKind { |
| 201 | DefaultInit, |
| 202 | AddressOf, |
| 203 | VarInit, |
| 204 | LValToRVal, |
| 205 | LifetimeBoundCall, |
| 206 | TemporaryCopy, |
| 207 | LambdaCaptureInit, |
| 208 | MemberExpr, |
| 209 | GslReferenceInit, |
| 210 | GslPointerInit, |
| 211 | GslPointerAssignment, |
| 212 | DefaultArg, |
| 213 | ParenAggInit, |
| 214 | } Kind; |
| 215 | Expr *E; |
| 216 | union { |
| 217 | const Decl *D = nullptr; |
| 218 | const LambdaCapture *Capture; |
| 219 | }; |
| 220 | IndirectLocalPathEntry() {} |
| 221 | IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {} |
| 222 | IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D) |
| 223 | : Kind(K), E(E), D(D) {} |
| 224 | IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture) |
| 225 | : Kind(K), E(E), Capture(Capture) {} |
| 226 | }; |
| 227 | |
| 228 | using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>; |
| 229 | |
| 230 | struct RevertToOldSizeRAII { |
| 231 | IndirectLocalPath &Path; |
| 232 | unsigned OldSize = Path.size(); |
| 233 | RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {} |
| 234 | ~RevertToOldSizeRAII() { Path.resize(N: OldSize); } |
| 235 | }; |
| 236 | |
| 237 | using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L, |
| 238 | ReferenceKind RK)>; |
| 239 | } // namespace |
| 240 | |
| 241 | static bool isVarOnPath(const IndirectLocalPath &Path, VarDecl *VD) { |
| 242 | for (auto E : Path) |
| 243 | if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD) |
| 244 | return true; |
| 245 | return false; |
| 246 | } |
| 247 | |
| 248 | static bool pathContainsInit(const IndirectLocalPath &Path) { |
| 249 | return llvm::any_of(Range: Path, P: [=](IndirectLocalPathEntry E) { |
| 250 | return E.Kind == IndirectLocalPathEntry::DefaultInit || |
| 251 | E.Kind == IndirectLocalPathEntry::VarInit; |
| 252 | }); |
| 253 | } |
| 254 | |
| 255 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, |
| 256 | Expr *Init, LocalVisitor Visit, |
| 257 | bool RevisitSubinits); |
| 258 | |
| 259 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, |
| 260 | Expr *Init, ReferenceKind RK, |
| 261 | LocalVisitor Visit); |
| 262 | |
| 263 | // Returns true if the given Record decl is a form of `GSLOwner<Pointer>` |
| 264 | // type, e.g. std::vector<string_view>, std::optional<string_view>. |
| 265 | static bool isContainerOfPointer(const RecordDecl *Container) { |
| 266 | if (const auto *CTSD = |
| 267 | dyn_cast_if_present<ClassTemplateSpecializationDecl>(Val: Container)) { |
| 268 | if (!CTSD->hasAttr<OwnerAttr>()) // Container must be a GSL owner type. |
| 269 | return false; |
| 270 | const auto &TAs = CTSD->getTemplateArgs(); |
| 271 | return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type && |
| 272 | lifetimes::isPointerLikeType(QT: TAs[0].getAsType()); |
| 273 | } |
| 274 | return false; |
| 275 | } |
| 276 | static bool isContainerOfOwner(const RecordDecl *Container) { |
| 277 | const auto *CTSD = |
| 278 | dyn_cast_if_present<ClassTemplateSpecializationDecl>(Val: Container); |
| 279 | if (!CTSD) |
| 280 | return false; |
| 281 | if (!CTSD->hasAttr<OwnerAttr>()) // Container must be a GSL owner type. |
| 282 | return false; |
| 283 | const auto &TAs = CTSD->getTemplateArgs(); |
| 284 | return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type && |
| 285 | isGslOwnerType(QT: TAs[0].getAsType()); |
| 286 | } |
| 287 | |
| 288 | // Returns true if the given Record is `std::initializer_list<pointer>`. |
| 289 | static bool isStdInitializerListOfPointer(const RecordDecl *RD) { |
| 290 | if (const auto *CTSD = |
| 291 | dyn_cast_if_present<ClassTemplateSpecializationDecl>(Val: RD)) { |
| 292 | const auto &TAs = CTSD->getTemplateArgs(); |
| 293 | return lifetimes::isInStlNamespace(D: RD) && RD->getIdentifier() && |
| 294 | RD->getName() == "initializer_list" && TAs.size() > 0 && |
| 295 | TAs[0].getKind() == TemplateArgument::Type && |
| 296 | lifetimes::isPointerLikeType(QT: TAs[0].getAsType()); |
| 297 | } |
| 298 | return false; |
| 299 | } |
| 300 | |
| 301 | // Returns true if the given constructor is a copy-like constructor, such as |
| 302 | // `Ctor(Owner<U>&&)` or `Ctor(const Owner<U>&)`. |
| 303 | static bool isCopyLikeConstructor(const CXXConstructorDecl *Ctor) { |
| 304 | if (!Ctor || Ctor->param_size() != 1) |
| 305 | return false; |
| 306 | const auto *ParamRefType = |
| 307 | Ctor->getParamDecl(i: 0)->getType()->getAs<ReferenceType>(); |
| 308 | if (!ParamRefType) |
| 309 | return false; |
| 310 | |
| 311 | // Check if the first parameter type is "Owner<U>". |
| 312 | if (const auto *TST = |
| 313 | ParamRefType->getPointeeType()->getAs<TemplateSpecializationType>()) |
| 314 | return TST->getTemplateName() |
| 315 | .getAsTemplateDecl() |
| 316 | ->getTemplatedDecl() |
| 317 | ->hasAttr<OwnerAttr>(); |
| 318 | return false; |
| 319 | } |
| 320 | |
| 321 | // Returns true if we should perform the GSL analysis on the first argument for |
| 322 | // the given constructor. |
| 323 | static bool |
| 324 | shouldTrackFirstArgumentForConstructor(const CXXConstructExpr *Ctor) { |
| 325 | const auto *LHSRecordDecl = Ctor->getConstructor()->getParent(); |
| 326 | |
| 327 | // Case 1, construct a GSL pointer, e.g. std::string_view |
| 328 | // Always inspect when LHS is a pointer. |
| 329 | if (LHSRecordDecl->hasAttr<PointerAttr>()) |
| 330 | return true; |
| 331 | |
| 332 | if (Ctor->getConstructor()->param_empty() || |
| 333 | !isContainerOfPointer(Container: LHSRecordDecl)) |
| 334 | return false; |
| 335 | |
| 336 | // Now, the LHS is an Owner<Pointer> type, e.g., std::vector<string_view>. |
| 337 | // |
| 338 | // At a high level, we cannot precisely determine what the nested pointer |
| 339 | // owns. However, by analyzing the RHS owner type, we can use heuristics to |
| 340 | // infer ownership information. These heuristics are designed to be |
| 341 | // conservative, minimizing false positives while still providing meaningful |
| 342 | // diagnostics. |
| 343 | // |
| 344 | // While this inference isn't perfect, it helps catch common use-after-free |
| 345 | // patterns. |
| 346 | auto RHSArgType = Ctor->getArg(Arg: 0)->getType(); |
| 347 | const auto *RHSRD = RHSArgType->getAsRecordDecl(); |
| 348 | // LHS is constructed from an initializer_list. |
| 349 | // |
| 350 | // std::initializer_list is a proxy object that provides access to the backing |
| 351 | // array. We perform analysis on it to determine if there are any dangling |
| 352 | // temporaries in the backing array. |
| 353 | // E.g. std::vector<string_view> abc = {string()}; |
| 354 | if (isStdInitializerListOfPointer(RD: RHSRD)) |
| 355 | return true; |
| 356 | |
| 357 | // RHS must be an owner. |
| 358 | if (!isGslOwnerType(QT: RHSArgType)) |
| 359 | return false; |
| 360 | |
| 361 | // Bail out if the RHS is Owner<Pointer>. |
| 362 | // |
| 363 | // We cannot reliably determine what the LHS nested pointer owns -- it could |
| 364 | // be the entire RHS or the nested pointer in RHS. To avoid false positives, |
| 365 | // we skip this case, such as: |
| 366 | // std::stack<std::string_view> s(std::deque<std::string_view>{}); |
| 367 | // |
| 368 | // TODO: this also has a false negative, it doesn't catch the case like: |
| 369 | // std::optional<span<int*>> os = std::vector<int*>{} |
| 370 | if (isContainerOfPointer(Container: RHSRD)) |
| 371 | return false; |
| 372 | |
| 373 | // Assume that the nested Pointer is constructed from the nested Owner. |
| 374 | // E.g. std::optional<string_view> sv = std::optional<string>(s); |
| 375 | if (isContainerOfOwner(Container: RHSRD)) |
| 376 | return true; |
| 377 | |
| 378 | // Now, the LHS is an Owner<Pointer> and the RHS is an Owner<X>, where X is |
| 379 | // neither an `Owner` nor a `Pointer`. |
| 380 | // |
| 381 | // Use the constructor's signature as a hint. If it is a copy-like constructor |
| 382 | // `Owner1<Pointer>(Owner2<X>&&)`, we assume that the nested pointer is |
| 383 | // constructed from X. In such cases, we do not diagnose, as `X` is not an |
| 384 | // owner, e.g. |
| 385 | // std::optional<string_view> sv = std::optional<Foo>(); |
| 386 | if (const auto *PrimaryCtorTemplate = |
| 387 | Ctor->getConstructor()->getPrimaryTemplate(); |
| 388 | PrimaryCtorTemplate && |
| 389 | isCopyLikeConstructor(Ctor: dyn_cast_if_present<CXXConstructorDecl>( |
| 390 | Val: PrimaryCtorTemplate->getTemplatedDecl()))) { |
| 391 | return false; |
| 392 | } |
| 393 | // Assume that the nested pointer is constructed from the whole RHS. |
| 394 | // E.g. optional<string_view> s = std::string(); |
| 395 | return true; |
| 396 | } |
| 397 | |
| 398 | // Visit lifetimebound or gsl-pointer arguments. |
| 399 | static void visitFunctionCallArguments(IndirectLocalPath &Path, Expr *Call, |
| 400 | LocalVisitor Visit) { |
| 401 | const FunctionDecl *Callee; |
| 402 | ArrayRef<Expr *> Args; |
| 403 | |
| 404 | if (auto *CE = dyn_cast<CallExpr>(Val: Call)) { |
| 405 | Callee = CE->getDirectCallee(); |
| 406 | Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs()); |
| 407 | } else { |
| 408 | auto *CCE = cast<CXXConstructExpr>(Val: Call); |
| 409 | Callee = CCE->getConstructor(); |
| 410 | Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()); |
| 411 | } |
| 412 | if (!Callee) |
| 413 | return; |
| 414 | |
| 415 | bool EnableGSLAnalysis = !Callee->getASTContext().getDiagnostics().isIgnored( |
| 416 | DiagID: diag::warn_dangling_lifetime_pointer, Loc: SourceLocation()); |
| 417 | Expr *ObjectArg = nullptr; |
| 418 | if (isa<CXXOperatorCallExpr>(Val: Call) && Callee->isCXXInstanceMember()) { |
| 419 | ObjectArg = Args[0]; |
| 420 | Args = Args.slice(N: 1); |
| 421 | } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: Call)) { |
| 422 | ObjectArg = MCE->getImplicitObjectArgument(); |
| 423 | } |
| 424 | |
| 425 | auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) { |
| 426 | Path.push_back(Elt: {IndirectLocalPathEntry::LifetimeBoundCall, Arg, D}); |
| 427 | if (Arg->isGLValue()) |
| 428 | visitLocalsRetainedByReferenceBinding(Path, Init: Arg, RK: RK_ReferenceBinding, |
| 429 | Visit); |
| 430 | else |
| 431 | visitLocalsRetainedByInitializer(Path, Init: Arg, Visit, RevisitSubinits: true); |
| 432 | Path.pop_back(); |
| 433 | }; |
| 434 | auto VisitGSLPointerArg = [&](const FunctionDecl *Callee, Expr *Arg) { |
| 435 | auto ReturnType = Callee->getReturnType(); |
| 436 | |
| 437 | // Once we initialized a value with a non gsl-owner reference, it can no |
| 438 | // longer dangle. |
| 439 | if (ReturnType->isReferenceType() && |
| 440 | !isGslOwnerType(QT: ReturnType->getPointeeType())) { |
| 441 | for (const IndirectLocalPathEntry &PE : llvm::reverse(C&: Path)) { |
| 442 | if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit || |
| 443 | PE.Kind == IndirectLocalPathEntry::LifetimeBoundCall) |
| 444 | continue; |
| 445 | if (PE.Kind == IndirectLocalPathEntry::GslPointerInit || |
| 446 | PE.Kind == IndirectLocalPathEntry::GslPointerAssignment) |
| 447 | return; |
| 448 | break; |
| 449 | } |
| 450 | } |
| 451 | Path.push_back(Elt: {ReturnType->isReferenceType() |
| 452 | ? IndirectLocalPathEntry::GslReferenceInit |
| 453 | : IndirectLocalPathEntry::GslPointerInit, |
| 454 | Arg, Callee}); |
| 455 | if (Arg->isGLValue()) |
| 456 | visitLocalsRetainedByReferenceBinding(Path, Init: Arg, RK: RK_ReferenceBinding, |
| 457 | Visit); |
| 458 | else |
| 459 | visitLocalsRetainedByInitializer(Path, Init: Arg, Visit, RevisitSubinits: true); |
| 460 | Path.pop_back(); |
| 461 | }; |
| 462 | |
| 463 | bool CheckCoroCall = false; |
| 464 | if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) { |
| 465 | CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() && |
| 466 | RD->hasAttr<CoroReturnTypeAttr>() && |
| 467 | !Callee->hasAttr<CoroDisableLifetimeBoundAttr>(); |
| 468 | } |
| 469 | |
| 470 | if (ObjectArg) { |
| 471 | bool CheckCoroObjArg = CheckCoroCall; |
| 472 | // Coroutine lambda objects with empty capture list are not lifetimebound. |
| 473 | if (auto *LE = dyn_cast<LambdaExpr>(Val: ObjectArg->IgnoreImplicit()); |
| 474 | LE && LE->captures().empty()) |
| 475 | CheckCoroObjArg = false; |
| 476 | // Allow `get_return_object()` as the object param (__promise) is not |
| 477 | // lifetimebound. |
| 478 | if (Sema::CanBeGetReturnObject(FD: Callee)) |
| 479 | CheckCoroObjArg = false; |
| 480 | if (lifetimes::implicitObjectParamIsLifetimeBound(FD: Callee) || |
| 481 | CheckCoroObjArg) |
| 482 | VisitLifetimeBoundArg(Callee, ObjectArg); |
| 483 | else if (EnableGSLAnalysis) { |
| 484 | if (auto *CME = dyn_cast<CXXMethodDecl>(Val: Callee); |
| 485 | CME && lifetimes::shouldTrackImplicitObjectArg( |
| 486 | Callee: CME, /*RunningUnderLifetimeSafety=*/false)) |
| 487 | VisitGSLPointerArg(Callee, ObjectArg); |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | const FunctionDecl *CanonCallee = |
| 492 | lifetimes::getDeclWithMergedLifetimeBoundAttrs(FD: Callee); |
| 493 | unsigned NP = std::min(a: Callee->getNumParams(), b: CanonCallee->getNumParams()); |
| 494 | for (unsigned I = 0, N = std::min<unsigned>(a: NP, b: Args.size()); I != N; ++I) { |
| 495 | Expr *Arg = Args[I]; |
| 496 | RevertToOldSizeRAII RAII(Path); |
| 497 | if (auto *DAE = dyn_cast<CXXDefaultArgExpr>(Val: Arg)) { |
| 498 | Path.push_back( |
| 499 | Elt: {IndirectLocalPathEntry::DefaultArg, DAE, DAE->getParam()}); |
| 500 | Arg = DAE->getExpr(); |
| 501 | } |
| 502 | if (CheckCoroCall || |
| 503 | CanonCallee->getParamDecl(i: I)->hasAttr<LifetimeBoundAttr>()) |
| 504 | VisitLifetimeBoundArg(CanonCallee->getParamDecl(i: I), Arg); |
| 505 | else if (const auto *CaptureAttr = |
| 506 | CanonCallee->getParamDecl(i: I)->getAttr<LifetimeCaptureByAttr>(); |
| 507 | CaptureAttr && isa<CXXConstructorDecl>(Val: CanonCallee) && |
| 508 | llvm::any_of(Range: CaptureAttr->params(), P: [](int ArgIdx) { |
| 509 | return ArgIdx == LifetimeCaptureByAttr::This; |
| 510 | })) |
| 511 | // `lifetime_capture_by(this)` in a class constructor has the same |
| 512 | // semantics as `lifetimebound`: |
| 513 | // |
| 514 | // struct Foo { |
| 515 | // const int& a; |
| 516 | // // Equivalent to Foo(const int& t [[clang::lifetimebound]]) |
| 517 | // Foo(const int& t [[clang::lifetime_capture_by(this)]]) : a(t) {} |
| 518 | // }; |
| 519 | // |
| 520 | // In the implementation, `lifetime_capture_by` is treated as an alias for |
| 521 | // `lifetimebound` and shares the same code path. This implies the emitted |
| 522 | // diagnostics will be emitted under `-Wdangling`, not |
| 523 | // `-Wdangling-capture`. |
| 524 | VisitLifetimeBoundArg(CanonCallee->getParamDecl(i: I), Arg); |
| 525 | else if (EnableGSLAnalysis && I == 0) { |
| 526 | // Perform GSL analysis for the first argument |
| 527 | if (lifetimes::shouldTrackFirstArgument(FD: CanonCallee)) { |
| 528 | VisitGSLPointerArg(CanonCallee, Arg); |
| 529 | } else if (auto *Ctor = dyn_cast<CXXConstructExpr>(Val: Call); |
| 530 | Ctor && shouldTrackFirstArgumentForConstructor(Ctor)) { |
| 531 | VisitGSLPointerArg(Ctor->getConstructor(), Arg); |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | /// Visit the locals that would be reachable through a reference bound to the |
| 538 | /// glvalue expression \c Init. |
| 539 | static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path, |
| 540 | Expr *Init, ReferenceKind RK, |
| 541 | LocalVisitor Visit) { |
| 542 | RevertToOldSizeRAII RAII(Path); |
| 543 | |
| 544 | // Walk past any constructs which we can lifetime-extend across. |
| 545 | Expr *Old; |
| 546 | do { |
| 547 | Old = Init; |
| 548 | |
| 549 | if (auto *FE = dyn_cast<FullExpr>(Val: Init)) |
| 550 | Init = FE->getSubExpr(); |
| 551 | |
| 552 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: Init)) { |
| 553 | // If this is just redundant braces around an initializer, step over it. |
| 554 | if (ILE->isTransparent()) |
| 555 | Init = ILE->getInit(Init: 0); |
| 556 | } |
| 557 | |
| 558 | if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Init->IgnoreImpCasts())) |
| 559 | Path.push_back( |
| 560 | Elt: {IndirectLocalPathEntry::MemberExpr, ME, ME->getMemberDecl()}); |
| 561 | // Step over any subobject adjustments; we may have a materialized |
| 562 | // temporary inside them. |
| 563 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); |
| 564 | |
| 565 | // Per current approach for DR1376, look through casts to reference type |
| 566 | // when performing lifetime extension. |
| 567 | if (CastExpr *CE = dyn_cast<CastExpr>(Val: Init)) |
| 568 | if (CE->getSubExpr()->isGLValue()) |
| 569 | Init = CE->getSubExpr(); |
| 570 | |
| 571 | // Per the current approach for DR1299, look through array element access |
| 572 | // on array glvalues when performing lifetime extension. |
| 573 | if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: Init)) { |
| 574 | Init = ASE->getBase(); |
| 575 | auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init); |
| 576 | if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay) |
| 577 | Init = ICE->getSubExpr(); |
| 578 | else |
| 579 | // We can't lifetime extend through this but we might still find some |
| 580 | // retained temporaries. |
| 581 | return visitLocalsRetainedByInitializer(Path, Init, Visit, RevisitSubinits: true); |
| 582 | } |
| 583 | |
| 584 | // Step into CXXDefaultInitExprs so we can diagnose cases where a |
| 585 | // constructor inherits one as an implicit mem-initializer. |
| 586 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Val: Init)) { |
| 587 | Path.push_back( |
| 588 | Elt: {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); |
| 589 | Init = DIE->getExpr(); |
| 590 | } |
| 591 | } while (Init != Old); |
| 592 | |
| 593 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Init)) { |
| 594 | if (Visit(Path, Local(MTE), RK)) |
| 595 | visitLocalsRetainedByInitializer(Path, Init: MTE->getSubExpr(), Visit, RevisitSubinits: true); |
| 596 | } |
| 597 | |
| 598 | if (auto *M = dyn_cast<MemberExpr>(Val: Init)) { |
| 599 | // Lifetime of a non-reference type field is same as base object. |
| 600 | if (auto *F = dyn_cast<FieldDecl>(Val: M->getMemberDecl()); |
| 601 | F && !F->getType()->isReferenceType()) |
| 602 | visitLocalsRetainedByInitializer(Path, Init: M->getBase(), Visit, RevisitSubinits: true); |
| 603 | } |
| 604 | |
| 605 | if (isa<CallExpr>(Val: Init)) |
| 606 | return visitFunctionCallArguments(Path, Call: Init, Visit); |
| 607 | |
| 608 | switch (Init->getStmtClass()) { |
| 609 | case Stmt::DeclRefExprClass: { |
| 610 | // If we find the name of a local non-reference parameter, we could have a |
| 611 | // lifetime problem. |
| 612 | auto *DRE = cast<DeclRefExpr>(Val: Init); |
| 613 | auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
| 614 | if (VD && VD->hasLocalStorage() && |
| 615 | !DRE->refersToEnclosingVariableOrCapture()) { |
| 616 | if (!VD->getType()->isReferenceType()) { |
| 617 | Visit(Path, Local(DRE), RK); |
| 618 | } else if (isa<ParmVarDecl>(Val: DRE->getDecl())) { |
| 619 | // The lifetime of a reference parameter is unknown; assume it's OK |
| 620 | // for now. |
| 621 | break; |
| 622 | } else if (VD->getInit() && !isVarOnPath(Path, VD)) { |
| 623 | Path.push_back(Elt: {IndirectLocalPathEntry::VarInit, DRE, VD}); |
| 624 | visitLocalsRetainedByReferenceBinding(Path, Init: VD->getInit(), |
| 625 | RK: RK_ReferenceBinding, Visit); |
| 626 | } |
| 627 | } |
| 628 | break; |
| 629 | } |
| 630 | |
| 631 | case Stmt::UnaryOperatorClass: { |
| 632 | // The only unary operator that make sense to handle here |
| 633 | // is Deref. All others don't resolve to a "name." This includes |
| 634 | // handling all sorts of rvalues passed to a unary operator. |
| 635 | const UnaryOperator *U = cast<UnaryOperator>(Val: Init); |
| 636 | if (U->getOpcode() == UO_Deref) |
| 637 | visitLocalsRetainedByInitializer(Path, Init: U->getSubExpr(), Visit, RevisitSubinits: true); |
| 638 | break; |
| 639 | } |
| 640 | |
| 641 | case Stmt::ArraySectionExprClass: { |
| 642 | visitLocalsRetainedByInitializer( |
| 643 | Path, Init: cast<ArraySectionExpr>(Val: Init)->getBase(), Visit, RevisitSubinits: true); |
| 644 | break; |
| 645 | } |
| 646 | |
| 647 | case Stmt::ConditionalOperatorClass: |
| 648 | case Stmt::BinaryConditionalOperatorClass: { |
| 649 | auto *C = cast<AbstractConditionalOperator>(Val: Init); |
| 650 | if (!C->getTrueExpr()->getType()->isVoidType()) |
| 651 | visitLocalsRetainedByReferenceBinding(Path, Init: C->getTrueExpr(), RK, Visit); |
| 652 | if (!C->getFalseExpr()->getType()->isVoidType()) |
| 653 | visitLocalsRetainedByReferenceBinding(Path, Init: C->getFalseExpr(), RK, Visit); |
| 654 | break; |
| 655 | } |
| 656 | |
| 657 | case Stmt::CompoundLiteralExprClass: { |
| 658 | if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Init)) { |
| 659 | if (!CLE->isFileScope()) |
| 660 | Visit(Path, Local(CLE), RK); |
| 661 | } |
| 662 | break; |
| 663 | } |
| 664 | |
| 665 | // FIXME: Visit the left-hand side of an -> or ->*. |
| 666 | |
| 667 | default: |
| 668 | break; |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | /// Visit the locals that would be reachable through an object initialized by |
| 673 | /// the prvalue expression \c Init. |
| 674 | static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path, |
| 675 | Expr *Init, LocalVisitor Visit, |
| 676 | bool RevisitSubinits) { |
| 677 | RevertToOldSizeRAII RAII(Path); |
| 678 | |
| 679 | Expr *Old; |
| 680 | do { |
| 681 | Old = Init; |
| 682 | |
| 683 | // Step into CXXDefaultInitExprs so we can diagnose cases where a |
| 684 | // constructor inherits one as an implicit mem-initializer. |
| 685 | if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Val: Init)) { |
| 686 | Path.push_back( |
| 687 | Elt: {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()}); |
| 688 | Init = DIE->getExpr(); |
| 689 | } |
| 690 | |
| 691 | if (auto *FE = dyn_cast<FullExpr>(Val: Init)) |
| 692 | Init = FE->getSubExpr(); |
| 693 | |
| 694 | // Dig out the expression which constructs the extended temporary. |
| 695 | Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments()); |
| 696 | |
| 697 | if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Init)) |
| 698 | Init = BTE->getSubExpr(); |
| 699 | |
| 700 | Init = Init->IgnoreParens(); |
| 701 | |
| 702 | // Step over value-preserving rvalue casts. |
| 703 | if (auto *CE = dyn_cast<CastExpr>(Val: Init)) { |
| 704 | switch (CE->getCastKind()) { |
| 705 | case CK_LValueToRValue: |
| 706 | // If we can match the lvalue to a const object, we can look at its |
| 707 | // initializer. |
| 708 | Path.push_back(Elt: {IndirectLocalPathEntry::LValToRVal, CE}); |
| 709 | return visitLocalsRetainedByReferenceBinding( |
| 710 | Path, Init, RK: RK_ReferenceBinding, |
| 711 | Visit: [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool { |
| 712 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: L)) { |
| 713 | auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
| 714 | if (VD && VD->getType().isConstQualified() && VD->getInit() && |
| 715 | !isVarOnPath(Path, VD)) { |
| 716 | Path.push_back(Elt: {IndirectLocalPathEntry::VarInit, DRE, VD}); |
| 717 | visitLocalsRetainedByInitializer(Path, Init: VD->getInit(), Visit, |
| 718 | RevisitSubinits: true); |
| 719 | } |
| 720 | } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: L)) { |
| 721 | if (MTE->getType().isConstQualified()) |
| 722 | visitLocalsRetainedByInitializer(Path, Init: MTE->getSubExpr(), |
| 723 | Visit, RevisitSubinits: true); |
| 724 | } |
| 725 | return false; |
| 726 | }); |
| 727 | |
| 728 | // We assume that objects can be retained by pointers cast to integers, |
| 729 | // but not if the integer is cast to floating-point type or to _Complex. |
| 730 | // We assume that casts to 'bool' do not preserve enough information to |
| 731 | // retain a local object. |
| 732 | case CK_NoOp: |
| 733 | case CK_BitCast: |
| 734 | case CK_BaseToDerived: |
| 735 | case CK_DerivedToBase: |
| 736 | case CK_UncheckedDerivedToBase: |
| 737 | case CK_Dynamic: |
| 738 | case CK_ToUnion: |
| 739 | case CK_UserDefinedConversion: |
| 740 | case CK_ConstructorConversion: |
| 741 | case CK_IntegralToPointer: |
| 742 | case CK_PointerToIntegral: |
| 743 | case CK_VectorSplat: |
| 744 | case CK_IntegralCast: |
| 745 | case CK_CPointerToObjCPointerCast: |
| 746 | case CK_BlockPointerToObjCPointerCast: |
| 747 | case CK_AnyPointerToBlockPointerCast: |
| 748 | case CK_AddressSpaceConversion: |
| 749 | break; |
| 750 | |
| 751 | case CK_ArrayToPointerDecay: |
| 752 | // Model array-to-pointer decay as taking the address of the array |
| 753 | // lvalue. |
| 754 | Path.push_back(Elt: {IndirectLocalPathEntry::AddressOf, CE}); |
| 755 | return visitLocalsRetainedByReferenceBinding( |
| 756 | Path, Init: CE->getSubExpr(), RK: RK_ReferenceBinding, Visit); |
| 757 | |
| 758 | default: |
| 759 | return; |
| 760 | } |
| 761 | |
| 762 | Init = CE->getSubExpr(); |
| 763 | } |
| 764 | } while (Old != Init); |
| 765 | |
| 766 | // C++17 [dcl.init.list]p6: |
| 767 | // initializing an initializer_list object from the array extends the |
| 768 | // lifetime of the array exactly like binding a reference to a temporary. |
| 769 | if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Val: Init)) |
| 770 | return visitLocalsRetainedByReferenceBinding(Path, Init: ILE->getSubExpr(), |
| 771 | RK: RK_StdInitializerList, Visit); |
| 772 | |
| 773 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: Init)) { |
| 774 | // We already visited the elements of this initializer list while |
| 775 | // performing the initialization. Don't visit them again unless we've |
| 776 | // changed the lifetime of the initialized entity. |
| 777 | if (!RevisitSubinits) |
| 778 | return; |
| 779 | |
| 780 | if (ILE->isTransparent()) |
| 781 | return visitLocalsRetainedByInitializer(Path, Init: ILE->getInit(Init: 0), Visit, |
| 782 | RevisitSubinits); |
| 783 | |
| 784 | if (ILE->getType()->isArrayType()) { |
| 785 | for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I) |
| 786 | visitLocalsRetainedByInitializer(Path, Init: ILE->getInit(Init: I), Visit, |
| 787 | RevisitSubinits); |
| 788 | return; |
| 789 | } |
| 790 | |
| 791 | if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) { |
| 792 | assert(RD->isAggregate() && "aggregate init on non-aggregate" ); |
| 793 | |
| 794 | // If we lifetime-extend a braced initializer which is initializing an |
| 795 | // aggregate, and that aggregate contains reference members which are |
| 796 | // bound to temporaries, those temporaries are also lifetime-extended. |
| 797 | if (RD->isUnion() && ILE->getInitializedFieldInUnion() && |
| 798 | ILE->getInitializedFieldInUnion()->getType()->isReferenceType()) |
| 799 | visitLocalsRetainedByReferenceBinding(Path, Init: ILE->getInit(Init: 0), |
| 800 | RK: RK_ReferenceBinding, Visit); |
| 801 | else { |
| 802 | unsigned Index = 0; |
| 803 | for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index) |
| 804 | visitLocalsRetainedByInitializer(Path, Init: ILE->getInit(Init: Index), Visit, |
| 805 | RevisitSubinits); |
| 806 | for (const auto *I : RD->fields()) { |
| 807 | if (Index >= ILE->getNumInits()) |
| 808 | break; |
| 809 | if (I->isUnnamedBitField()) |
| 810 | continue; |
| 811 | Expr *SubInit = ILE->getInit(Init: Index); |
| 812 | if (I->getType()->isReferenceType()) |
| 813 | visitLocalsRetainedByReferenceBinding(Path, Init: SubInit, |
| 814 | RK: RK_ReferenceBinding, Visit); |
| 815 | else |
| 816 | // This might be either aggregate-initialization of a member or |
| 817 | // initialization of a std::initializer_list object. Regardless, |
| 818 | // we should recursively lifetime-extend that initializer. |
| 819 | visitLocalsRetainedByInitializer(Path, Init: SubInit, Visit, |
| 820 | RevisitSubinits); |
| 821 | ++Index; |
| 822 | } |
| 823 | } |
| 824 | } |
| 825 | return; |
| 826 | } |
| 827 | |
| 828 | // The lifetime of an init-capture is that of the closure object constructed |
| 829 | // by a lambda-expression. |
| 830 | if (auto *LE = dyn_cast<LambdaExpr>(Val: Init)) { |
| 831 | LambdaExpr::capture_iterator CapI = LE->capture_begin(); |
| 832 | for (Expr *E : LE->capture_inits()) { |
| 833 | assert(CapI != LE->capture_end()); |
| 834 | const LambdaCapture &Cap = *CapI++; |
| 835 | if (!E) |
| 836 | continue; |
| 837 | if (Cap.capturesVariable()) |
| 838 | Path.push_back(Elt: {IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap}); |
| 839 | if (E->isGLValue()) |
| 840 | visitLocalsRetainedByReferenceBinding(Path, Init: E, RK: RK_ReferenceBinding, |
| 841 | Visit); |
| 842 | else |
| 843 | visitLocalsRetainedByInitializer(Path, Init: E, Visit, RevisitSubinits: true); |
| 844 | if (Cap.capturesVariable()) |
| 845 | Path.pop_back(); |
| 846 | } |
| 847 | } |
| 848 | |
| 849 | // Assume that a copy or move from a temporary references the same objects |
| 850 | // that the temporary does. |
| 851 | if (auto *CCE = dyn_cast<CXXConstructExpr>(Val: Init)) { |
| 852 | if (CCE->getConstructor()->isCopyOrMoveConstructor()) { |
| 853 | if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: CCE->getArg(Arg: 0))) { |
| 854 | Expr *Arg = MTE->getSubExpr(); |
| 855 | Path.push_back(Elt: {IndirectLocalPathEntry::TemporaryCopy, Arg, |
| 856 | CCE->getConstructor()}); |
| 857 | visitLocalsRetainedByInitializer(Path, Init: Arg, Visit, RevisitSubinits: true); |
| 858 | Path.pop_back(); |
| 859 | } |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | if (isa<CallExpr>(Val: Init) || isa<CXXConstructExpr>(Val: Init)) |
| 864 | return visitFunctionCallArguments(Path, Call: Init, Visit); |
| 865 | |
| 866 | if (auto *CPE = dyn_cast<CXXParenListInitExpr>(Val: Init)) { |
| 867 | RevertToOldSizeRAII RAII(Path); |
| 868 | Path.push_back(Elt: {IndirectLocalPathEntry::ParenAggInit, CPE}); |
| 869 | for (auto *I : CPE->getInitExprs()) { |
| 870 | if (I->isGLValue()) |
| 871 | visitLocalsRetainedByReferenceBinding(Path, Init: I, RK: RK_ReferenceBinding, |
| 872 | Visit); |
| 873 | else |
| 874 | visitLocalsRetainedByInitializer(Path, Init: I, Visit, RevisitSubinits: true); |
| 875 | } |
| 876 | } |
| 877 | switch (Init->getStmtClass()) { |
| 878 | case Stmt::UnaryOperatorClass: { |
| 879 | auto *UO = cast<UnaryOperator>(Val: Init); |
| 880 | // If the initializer is the address of a local, we could have a lifetime |
| 881 | // problem. |
| 882 | if (UO->getOpcode() == UO_AddrOf) { |
| 883 | // If this is &rvalue, then it's ill-formed and we have already diagnosed |
| 884 | // it. Don't produce a redundant warning about the lifetime of the |
| 885 | // temporary. |
| 886 | if (isa<MaterializeTemporaryExpr>(Val: UO->getSubExpr())) |
| 887 | return; |
| 888 | |
| 889 | Path.push_back(Elt: {IndirectLocalPathEntry::AddressOf, UO}); |
| 890 | visitLocalsRetainedByReferenceBinding(Path, Init: UO->getSubExpr(), |
| 891 | RK: RK_ReferenceBinding, Visit); |
| 892 | } |
| 893 | break; |
| 894 | } |
| 895 | |
| 896 | case Stmt::BinaryOperatorClass: { |
| 897 | // Handle pointer arithmetic. |
| 898 | auto *BO = cast<BinaryOperator>(Val: Init); |
| 899 | BinaryOperatorKind BOK = BO->getOpcode(); |
| 900 | if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub)) |
| 901 | break; |
| 902 | |
| 903 | if (BO->getLHS()->getType()->isPointerType()) |
| 904 | visitLocalsRetainedByInitializer(Path, Init: BO->getLHS(), Visit, RevisitSubinits: true); |
| 905 | else if (BO->getRHS()->getType()->isPointerType()) |
| 906 | visitLocalsRetainedByInitializer(Path, Init: BO->getRHS(), Visit, RevisitSubinits: true); |
| 907 | break; |
| 908 | } |
| 909 | |
| 910 | case Stmt::ConditionalOperatorClass: |
| 911 | case Stmt::BinaryConditionalOperatorClass: { |
| 912 | auto *C = cast<AbstractConditionalOperator>(Val: Init); |
| 913 | // In C++, we can have a throw-expression operand, which has 'void' type |
| 914 | // and isn't interesting from a lifetime perspective. |
| 915 | if (!C->getTrueExpr()->getType()->isVoidType()) |
| 916 | visitLocalsRetainedByInitializer(Path, Init: C->getTrueExpr(), Visit, RevisitSubinits: true); |
| 917 | if (!C->getFalseExpr()->getType()->isVoidType()) |
| 918 | visitLocalsRetainedByInitializer(Path, Init: C->getFalseExpr(), Visit, RevisitSubinits: true); |
| 919 | break; |
| 920 | } |
| 921 | |
| 922 | case Stmt::BlockExprClass: |
| 923 | if (cast<BlockExpr>(Val: Init)->getBlockDecl()->hasCaptures()) { |
| 924 | // This is a local block, whose lifetime is that of the function. |
| 925 | Visit(Path, Local(cast<BlockExpr>(Val: Init)), RK_ReferenceBinding); |
| 926 | } |
| 927 | break; |
| 928 | |
| 929 | case Stmt::AddrLabelExprClass: |
| 930 | // We want to warn if the address of a label would escape the function. |
| 931 | Visit(Path, Local(cast<AddrLabelExpr>(Val: Init)), RK_ReferenceBinding); |
| 932 | break; |
| 933 | |
| 934 | default: |
| 935 | break; |
| 936 | } |
| 937 | } |
| 938 | |
| 939 | /// Whether a path to an object supports lifetime extension. |
| 940 | enum PathLifetimeKind { |
| 941 | /// Lifetime-extend along this path. |
| 942 | Extend, |
| 943 | /// Do not lifetime extend along this path. |
| 944 | NoExtend |
| 945 | }; |
| 946 | |
| 947 | /// Determine whether this is an indirect path to a temporary that we are |
| 948 | /// supposed to lifetime-extend along. |
| 949 | static PathLifetimeKind |
| 950 | shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) { |
| 951 | for (auto Elem : Path) { |
| 952 | if (Elem.Kind == IndirectLocalPathEntry::MemberExpr || |
| 953 | Elem.Kind == IndirectLocalPathEntry::LambdaCaptureInit) |
| 954 | continue; |
| 955 | return Elem.Kind == IndirectLocalPathEntry::DefaultInit |
| 956 | ? PathLifetimeKind::Extend |
| 957 | : PathLifetimeKind::NoExtend; |
| 958 | } |
| 959 | return PathLifetimeKind::Extend; |
| 960 | } |
| 961 | |
| 962 | /// Find the range for the first interesting entry in the path at or after I. |
| 963 | static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I, |
| 964 | Expr *E) { |
| 965 | for (unsigned N = Path.size(); I != N; ++I) { |
| 966 | switch (Path[I].Kind) { |
| 967 | case IndirectLocalPathEntry::AddressOf: |
| 968 | case IndirectLocalPathEntry::LValToRVal: |
| 969 | case IndirectLocalPathEntry::LifetimeBoundCall: |
| 970 | case IndirectLocalPathEntry::TemporaryCopy: |
| 971 | case IndirectLocalPathEntry::GslReferenceInit: |
| 972 | case IndirectLocalPathEntry::GslPointerInit: |
| 973 | case IndirectLocalPathEntry::GslPointerAssignment: |
| 974 | case IndirectLocalPathEntry::ParenAggInit: |
| 975 | case IndirectLocalPathEntry::MemberExpr: |
| 976 | // These exist primarily to mark the path as not permitting or |
| 977 | // supporting lifetime extension. |
| 978 | break; |
| 979 | |
| 980 | case IndirectLocalPathEntry::VarInit: |
| 981 | if (cast<VarDecl>(Val: Path[I].D)->isImplicit()) |
| 982 | return SourceRange(); |
| 983 | [[fallthrough]]; |
| 984 | case IndirectLocalPathEntry::DefaultInit: |
| 985 | return Path[I].E->getSourceRange(); |
| 986 | |
| 987 | case IndirectLocalPathEntry::LambdaCaptureInit: |
| 988 | if (!Path[I].Capture->capturesVariable()) |
| 989 | continue; |
| 990 | return Path[I].E->getSourceRange(); |
| 991 | |
| 992 | case IndirectLocalPathEntry::DefaultArg: |
| 993 | return cast<CXXDefaultArgExpr>(Val: Path[I].E)->getUsedLocation(); |
| 994 | } |
| 995 | } |
| 996 | return E->getSourceRange(); |
| 997 | } |
| 998 | |
| 999 | static bool pathOnlyHandlesGslPointer(const IndirectLocalPath &Path) { |
| 1000 | for (const auto &It : llvm::reverse(C: Path)) { |
| 1001 | switch (It.Kind) { |
| 1002 | case IndirectLocalPathEntry::VarInit: |
| 1003 | case IndirectLocalPathEntry::AddressOf: |
| 1004 | case IndirectLocalPathEntry::LifetimeBoundCall: |
| 1005 | case IndirectLocalPathEntry::MemberExpr: |
| 1006 | continue; |
| 1007 | case IndirectLocalPathEntry::GslPointerInit: |
| 1008 | case IndirectLocalPathEntry::GslReferenceInit: |
| 1009 | case IndirectLocalPathEntry::GslPointerAssignment: |
| 1010 | return true; |
| 1011 | default: |
| 1012 | return false; |
| 1013 | } |
| 1014 | } |
| 1015 | return false; |
| 1016 | } |
| 1017 | // Result of analyzing the Path for GSLPointer. |
| 1018 | enum AnalysisResult { |
| 1019 | // Path does not correspond to a GSLPointer. |
| 1020 | NotGSLPointer, |
| 1021 | |
| 1022 | // A relevant case was identified. |
| 1023 | Report, |
| 1024 | // Stop the entire traversal. |
| 1025 | Abandon, |
| 1026 | // Skip this step and continue traversing inner AST nodes. |
| 1027 | Skip, |
| 1028 | }; |
| 1029 | // Analyze cases where a GSLPointer is initialized or assigned from a |
| 1030 | // temporary owner object. |
| 1031 | static AnalysisResult analyzePathForGSLPointer(const IndirectLocalPath &Path, |
| 1032 | Local L, LifetimeKind LK) { |
| 1033 | if (!pathOnlyHandlesGslPointer(Path)) |
| 1034 | return NotGSLPointer; |
| 1035 | |
| 1036 | // At this point, Path represents a series of operations involving a |
| 1037 | // GSLPointer, either in the process of initialization or assignment. |
| 1038 | |
| 1039 | // Process temporary base objects for MemberExpr cases, e.g. Temp().field. |
| 1040 | for (const auto &E : Path) { |
| 1041 | if (E.Kind == IndirectLocalPathEntry::MemberExpr) { |
| 1042 | // Avoid interfering with the local base object. |
| 1043 | if (pathContainsInit(Path)) |
| 1044 | return Abandon; |
| 1045 | |
| 1046 | // We are not interested in the temporary base objects of gsl Pointers: |
| 1047 | // auto p1 = Temp().ptr; // Here p1 might not dangle. |
| 1048 | // However, we want to diagnose for gsl owner fields: |
| 1049 | // auto p2 = Temp().owner; // Here p2 is dangling. |
| 1050 | if (const auto *FD = llvm::dyn_cast_or_null<FieldDecl>(Val: E.D); |
| 1051 | FD && !FD->getType()->isReferenceType() && |
| 1052 | isGslOwnerType(QT: FD->getType()) && LK != LK_MemInitializer) { |
| 1053 | return Report; |
| 1054 | } |
| 1055 | return Abandon; |
| 1056 | } |
| 1057 | } |
| 1058 | |
| 1059 | // Note: A LifetimeBoundCall can appear interleaved in this sequence. |
| 1060 | // For example: |
| 1061 | // const std::string& Ref(const std::string& a [[clang::lifetimebound]]); |
| 1062 | // string_view abc = Ref(std::string()); |
| 1063 | // The "Path" is [GSLPointerInit, LifetimeboundCall], where "L" is the |
| 1064 | // temporary "std::string()" object. We need to check the return type of the |
| 1065 | // function with the lifetimebound attribute. |
| 1066 | if (Path.back().Kind == IndirectLocalPathEntry::LifetimeBoundCall) { |
| 1067 | // The lifetimebound applies to the implicit object parameter of a method. |
| 1068 | const FunctionDecl *FD = |
| 1069 | llvm::dyn_cast_or_null<FunctionDecl>(Val: Path.back().D); |
| 1070 | // The lifetimebound applies to a function parameter. |
| 1071 | if (const auto *PD = llvm::dyn_cast<ParmVarDecl>(Val: Path.back().D)) |
| 1072 | FD = llvm::dyn_cast<FunctionDecl>(Val: PD->getDeclContext()); |
| 1073 | |
| 1074 | if (isa_and_present<CXXConstructorDecl>(Val: FD)) { |
| 1075 | // Constructor case: the parameter is annotated with lifetimebound |
| 1076 | // e.g., GSLPointer(const S& s [[clang::lifetimebound]]) |
| 1077 | // We still respect this case even the type S is not an owner. |
| 1078 | return Report; |
| 1079 | } |
| 1080 | // Check the return type, e.g. |
| 1081 | // const GSLOwner& func(const Foo& foo [[clang::lifetimebound]]) |
| 1082 | // GSLOwner* func(cosnt Foo& foo [[clang::lifetimebound]]) |
| 1083 | // GSLPointer func(const Foo& foo [[clang::lifetimebound]]) |
| 1084 | if (FD && ((FD->getReturnType()->isPointerOrReferenceType() && |
| 1085 | isGslOwnerType(QT: FD->getReturnType()->getPointeeType())) || |
| 1086 | isGslPointerType(QT: FD->getReturnType()))) |
| 1087 | return Report; |
| 1088 | |
| 1089 | return Abandon; |
| 1090 | } |
| 1091 | |
| 1092 | if (isa<DeclRefExpr>(Val: L)) { |
| 1093 | // We do not want to follow the references when returning a pointer |
| 1094 | // originating from a local owner to avoid the following false positive: |
| 1095 | // int &p = *localUniquePtr; |
| 1096 | // someContainer.add(std::move(localUniquePtr)); |
| 1097 | // return p; |
| 1098 | if (!pathContainsInit(Path) && isGslOwnerType(QT: L->getType())) |
| 1099 | return Report; |
| 1100 | return Abandon; |
| 1101 | } |
| 1102 | |
| 1103 | // The GSLPointer is from a temporary object. |
| 1104 | auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: L); |
| 1105 | |
| 1106 | bool IsGslPtrValueFromGslTempOwner = |
| 1107 | MTE && !MTE->getExtendingDecl() && isGslOwnerType(QT: MTE->getType()); |
| 1108 | // Skipping a chain of initializing gsl::Pointer annotated objects. |
| 1109 | // We are looking only for the final source to find out if it was |
| 1110 | // a local or temporary owner or the address of a local |
| 1111 | // variable/param. |
| 1112 | if (!IsGslPtrValueFromGslTempOwner) |
| 1113 | return Skip; |
| 1114 | return Report; |
| 1115 | } |
| 1116 | |
| 1117 | static bool shouldRunGSLAssignmentAnalysis(const Sema &SemaRef, |
| 1118 | const AssignedEntity &Entity) { |
| 1119 | bool EnableGSLAssignmentWarnings = !SemaRef.getDiagnostics().isIgnored( |
| 1120 | DiagID: diag::warn_dangling_lifetime_pointer_assignment, Loc: SourceLocation()); |
| 1121 | return (EnableGSLAssignmentWarnings && |
| 1122 | (isGslPointerType(QT: Entity.LHS->getType()) || |
| 1123 | lifetimes::isAssignmentOperatorLifetimeBound( |
| 1124 | CMD: Entity.AssignmentOperator))); |
| 1125 | } |
| 1126 | |
| 1127 | static void |
| 1128 | checkExprLifetimeImpl(Sema &SemaRef, const InitializedEntity *InitEntity, |
| 1129 | const InitializedEntity *ExtendingEntity, LifetimeKind LK, |
| 1130 | const AssignedEntity *AEntity, |
| 1131 | const CapturingEntity *CapEntity, Expr *Init) { |
| 1132 | assert(!AEntity || LK == LK_Assignment); |
| 1133 | assert(!CapEntity || LK == LK_LifetimeCapture); |
| 1134 | assert(!InitEntity || (LK != LK_Assignment && LK != LK_LifetimeCapture)); |
| 1135 | // If this entity doesn't have an interesting lifetime, don't bother looking |
| 1136 | // for temporaries within its initializer. |
| 1137 | if (LK == LK_FullExpression) |
| 1138 | return; |
| 1139 | |
| 1140 | // FIXME: consider moving the TemporaryVisitor and visitLocalsRetained* |
| 1141 | // functions to a dedicated class. |
| 1142 | auto TemporaryVisitor = [&](const IndirectLocalPath &Path, Local L, |
| 1143 | ReferenceKind RK) -> bool { |
| 1144 | SourceRange DiagRange = nextPathEntryRange(Path, I: 0, E: L); |
| 1145 | SourceLocation DiagLoc = DiagRange.getBegin(); |
| 1146 | |
| 1147 | auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: L); |
| 1148 | |
| 1149 | bool IsGslPtrValueFromGslTempOwner = true; |
| 1150 | switch (analyzePathForGSLPointer(Path, L, LK)) { |
| 1151 | case Abandon: |
| 1152 | return false; |
| 1153 | case Skip: |
| 1154 | return true; |
| 1155 | case NotGSLPointer: |
| 1156 | IsGslPtrValueFromGslTempOwner = false; |
| 1157 | [[fallthrough]]; |
| 1158 | case Report: |
| 1159 | break; |
| 1160 | } |
| 1161 | |
| 1162 | switch (LK) { |
| 1163 | case LK_FullExpression: |
| 1164 | llvm_unreachable("already handled this" ); |
| 1165 | |
| 1166 | case LK_Extended: { |
| 1167 | if (!MTE) { |
| 1168 | // The initialized entity has lifetime beyond the full-expression, |
| 1169 | // and the local entity does too, so don't warn. |
| 1170 | // |
| 1171 | // FIXME: We should consider warning if a static / thread storage |
| 1172 | // duration variable retains an automatic storage duration local. |
| 1173 | return false; |
| 1174 | } |
| 1175 | |
| 1176 | switch (shouldLifetimeExtendThroughPath(Path)) { |
| 1177 | case PathLifetimeKind::Extend: |
| 1178 | // Update the storage duration of the materialized temporary. |
| 1179 | // FIXME: Rebuild the expression instead of mutating it. |
| 1180 | MTE->setExtendingDecl(ExtendedBy: ExtendingEntity->getDecl(), |
| 1181 | ManglingNumber: ExtendingEntity->allocateManglingNumber()); |
| 1182 | // Also visit the temporaries lifetime-extended by this initializer. |
| 1183 | return true; |
| 1184 | |
| 1185 | case PathLifetimeKind::NoExtend: |
| 1186 | if (SemaRef.getLangOpts().CPlusPlus23 && InitEntity) { |
| 1187 | if (const VarDecl *VD = |
| 1188 | dyn_cast_if_present<VarDecl>(Val: InitEntity->getDecl()); |
| 1189 | VD && VD->isCXXForRangeImplicitVar()) { |
| 1190 | return false; |
| 1191 | } |
| 1192 | } |
| 1193 | |
| 1194 | if (IsGslPtrValueFromGslTempOwner && DiagLoc.isValid()) { |
| 1195 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_dangling_lifetime_pointer) |
| 1196 | << DiagRange; |
| 1197 | return false; |
| 1198 | } |
| 1199 | |
| 1200 | // If the path goes through the initialization of a variable or field, |
| 1201 | // it can't possibly reach a temporary created in this full-expression. |
| 1202 | // We will have already diagnosed any problems with the initializer. |
| 1203 | if (pathContainsInit(Path)) |
| 1204 | return false; |
| 1205 | |
| 1206 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_dangling_variable) |
| 1207 | << RK << !InitEntity->getParent() |
| 1208 | << ExtendingEntity->getDecl()->isImplicit() |
| 1209 | << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange; |
| 1210 | break; |
| 1211 | } |
| 1212 | break; |
| 1213 | } |
| 1214 | |
| 1215 | case LK_LifetimeCapture: { |
| 1216 | // The captured entity has lifetime beyond the full-expression, |
| 1217 | // and the capturing entity does too, so don't warn. |
| 1218 | if (!MTE) |
| 1219 | return false; |
| 1220 | if (CapEntity->Entity) |
| 1221 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_dangling_reference_captured) |
| 1222 | << CapEntity->Entity << DiagRange; |
| 1223 | else |
| 1224 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_dangling_reference_captured_by_unknown) |
| 1225 | << DiagRange; |
| 1226 | return false; |
| 1227 | } |
| 1228 | |
| 1229 | case LK_Assignment: { |
| 1230 | if (!MTE || pathContainsInit(Path)) |
| 1231 | return false; |
| 1232 | if (IsGslPtrValueFromGslTempOwner) |
| 1233 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_dangling_lifetime_pointer_assignment) |
| 1234 | << AEntity->LHS << DiagRange; |
| 1235 | else |
| 1236 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_dangling_pointer_assignment) |
| 1237 | << AEntity->LHS->getType()->isPointerType() << AEntity->LHS |
| 1238 | << DiagRange; |
| 1239 | return false; |
| 1240 | } |
| 1241 | case LK_MemInitializer: { |
| 1242 | if (MTE) { |
| 1243 | // Under C++ DR1696, if a mem-initializer (or a default member |
| 1244 | // initializer used by the absence of one) would lifetime-extend a |
| 1245 | // temporary, the program is ill-formed. |
| 1246 | if (auto *ExtendingDecl = |
| 1247 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { |
| 1248 | if (IsGslPtrValueFromGslTempOwner) { |
| 1249 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_dangling_lifetime_pointer_member) |
| 1250 | << ExtendingDecl << DiagRange; |
| 1251 | SemaRef.Diag(Loc: ExtendingDecl->getLocation(), |
| 1252 | DiagID: diag::note_ref_or_ptr_member_declared_here) |
| 1253 | << true; |
| 1254 | return false; |
| 1255 | } |
| 1256 | bool IsSubobjectMember = ExtendingEntity != InitEntity; |
| 1257 | SemaRef.Diag(Loc: DiagLoc, DiagID: shouldLifetimeExtendThroughPath(Path) != |
| 1258 | PathLifetimeKind::NoExtend |
| 1259 | ? diag::err_dangling_member |
| 1260 | : diag::warn_dangling_member) |
| 1261 | << ExtendingDecl << IsSubobjectMember << RK << DiagRange; |
| 1262 | // Don't bother adding a note pointing to the field if we're inside |
| 1263 | // its default member initializer; our primary diagnostic points to |
| 1264 | // the same place in that case. |
| 1265 | if (Path.empty() || |
| 1266 | Path.back().Kind != IndirectLocalPathEntry::DefaultInit) { |
| 1267 | SemaRef.Diag(Loc: ExtendingDecl->getLocation(), |
| 1268 | DiagID: diag::note_lifetime_extending_member_declared_here) |
| 1269 | << RK << IsSubobjectMember; |
| 1270 | } |
| 1271 | } else { |
| 1272 | // We have a mem-initializer but no particular field within it; this |
| 1273 | // is either a base class or a delegating initializer directly |
| 1274 | // initializing the base-class from something that doesn't live long |
| 1275 | // enough. |
| 1276 | // |
| 1277 | // FIXME: Warn on this. |
| 1278 | return false; |
| 1279 | } |
| 1280 | } else { |
| 1281 | // Paths via a default initializer can only occur during error recovery |
| 1282 | // (there's no other way that a default initializer can refer to a |
| 1283 | // local). Don't produce a bogus warning on those cases. |
| 1284 | if (pathContainsInit(Path)) |
| 1285 | return false; |
| 1286 | |
| 1287 | auto *DRE = dyn_cast<DeclRefExpr>(Val: L); |
| 1288 | // Suppress false positives for code like the one below: |
| 1289 | // Ctor(unique_ptr<T> up) : pointer(up.get()), owner(move(up)) {} |
| 1290 | // FIXME: move this logic to analyzePathForGSLPointer. |
| 1291 | if (DRE && isGslOwnerType(QT: DRE->getType())) |
| 1292 | return false; |
| 1293 | |
| 1294 | auto *VD = DRE ? dyn_cast<VarDecl>(Val: DRE->getDecl()) : nullptr; |
| 1295 | if (!VD) { |
| 1296 | // A member was initialized to a local block. |
| 1297 | // FIXME: Warn on this. |
| 1298 | return false; |
| 1299 | } |
| 1300 | |
| 1301 | if (auto *Member = |
| 1302 | ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) { |
| 1303 | bool IsPointer = !Member->getType()->isReferenceType(); |
| 1304 | SemaRef.Diag(Loc: DiagLoc, |
| 1305 | DiagID: IsPointer ? diag::warn_init_ptr_member_to_parameter_addr |
| 1306 | : diag::warn_bind_ref_member_to_parameter) |
| 1307 | << Member << VD << isa<ParmVarDecl>(Val: VD) << DiagRange; |
| 1308 | SemaRef.Diag(Loc: Member->getLocation(), |
| 1309 | DiagID: diag::note_ref_or_ptr_member_declared_here) |
| 1310 | << (unsigned)IsPointer; |
| 1311 | } |
| 1312 | } |
| 1313 | break; |
| 1314 | } |
| 1315 | |
| 1316 | case LK_New: |
| 1317 | if (isa<MaterializeTemporaryExpr>(Val: L)) { |
| 1318 | if (IsGslPtrValueFromGslTempOwner) |
| 1319 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_dangling_lifetime_pointer) |
| 1320 | << DiagRange; |
| 1321 | else |
| 1322 | SemaRef.Diag(Loc: DiagLoc, DiagID: RK == RK_ReferenceBinding |
| 1323 | ? diag::warn_new_dangling_reference |
| 1324 | : diag::warn_new_dangling_initializer_list) |
| 1325 | << !InitEntity->getParent() << DiagRange; |
| 1326 | } else { |
| 1327 | // We can't determine if the allocation outlives the local declaration. |
| 1328 | return false; |
| 1329 | } |
| 1330 | break; |
| 1331 | |
| 1332 | case LK_Return: |
| 1333 | case LK_MustTail: |
| 1334 | case LK_StmtExprResult: |
| 1335 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: L)) { |
| 1336 | // We can't determine if the local variable outlives the statement |
| 1337 | // expression. |
| 1338 | if (LK == LK_StmtExprResult) |
| 1339 | return false; |
| 1340 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_ret_stack_addr_ref) |
| 1341 | << InitEntity->getType()->isReferenceType() << DRE->getDecl() |
| 1342 | << isa<ParmVarDecl>(Val: DRE->getDecl()) << (LK == LK_MustTail) |
| 1343 | << DiagRange; |
| 1344 | } else if (isa<BlockExpr>(Val: L)) { |
| 1345 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::err_ret_local_block) << DiagRange; |
| 1346 | } else if (isa<AddrLabelExpr>(Val: L)) { |
| 1347 | // Don't warn when returning a label from a statement expression. |
| 1348 | // Leaving the scope doesn't end its lifetime. |
| 1349 | if (LK == LK_StmtExprResult) |
| 1350 | return false; |
| 1351 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_ret_addr_label) << DiagRange; |
| 1352 | } else if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: L)) { |
| 1353 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_ret_stack_addr_ref) |
| 1354 | << InitEntity->getType()->isReferenceType() << CLE->getInitializer() |
| 1355 | << 2 << (LK == LK_MustTail) << DiagRange; |
| 1356 | } else { |
| 1357 | // P2748R5: Disallow Binding a Returned Glvalue to a Temporary. |
| 1358 | // [stmt.return]/p6: In a function whose return type is a reference, |
| 1359 | // other than an invented function for std::is_convertible ([meta.rel]), |
| 1360 | // a return statement that binds the returned reference to a temporary |
| 1361 | // expression ([class.temporary]) is ill-formed. |
| 1362 | if (SemaRef.getLangOpts().CPlusPlus26 && |
| 1363 | InitEntity->getType()->isReferenceType()) |
| 1364 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::err_ret_local_temp_ref) |
| 1365 | << InitEntity->getType()->isReferenceType() << DiagRange; |
| 1366 | else if (LK == LK_MustTail) |
| 1367 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_musttail_local_temp_addr_ref) |
| 1368 | << InitEntity->getType()->isReferenceType() << DiagRange; |
| 1369 | else |
| 1370 | SemaRef.Diag(Loc: DiagLoc, DiagID: diag::warn_ret_local_temp_addr_ref) |
| 1371 | << InitEntity->getType()->isReferenceType() << DiagRange; |
| 1372 | } |
| 1373 | break; |
| 1374 | } |
| 1375 | |
| 1376 | for (unsigned I = 0; I != Path.size(); ++I) { |
| 1377 | auto Elem = Path[I]; |
| 1378 | |
| 1379 | switch (Elem.Kind) { |
| 1380 | case IndirectLocalPathEntry::AddressOf: |
| 1381 | case IndirectLocalPathEntry::LValToRVal: |
| 1382 | case IndirectLocalPathEntry::ParenAggInit: |
| 1383 | // These exist primarily to mark the path as not permitting or |
| 1384 | // supporting lifetime extension. |
| 1385 | break; |
| 1386 | |
| 1387 | case IndirectLocalPathEntry::LifetimeBoundCall: |
| 1388 | case IndirectLocalPathEntry::TemporaryCopy: |
| 1389 | case IndirectLocalPathEntry::MemberExpr: |
| 1390 | case IndirectLocalPathEntry::GslPointerInit: |
| 1391 | case IndirectLocalPathEntry::GslReferenceInit: |
| 1392 | case IndirectLocalPathEntry::GslPointerAssignment: |
| 1393 | // FIXME: Consider adding a note for these. |
| 1394 | break; |
| 1395 | |
| 1396 | case IndirectLocalPathEntry::DefaultInit: { |
| 1397 | auto *FD = cast<FieldDecl>(Val: Elem.D); |
| 1398 | SemaRef.Diag(Loc: FD->getLocation(), |
| 1399 | DiagID: diag::note_init_with_default_member_initializer) |
| 1400 | << FD << nextPathEntryRange(Path, I: I + 1, E: L); |
| 1401 | break; |
| 1402 | } |
| 1403 | |
| 1404 | case IndirectLocalPathEntry::VarInit: { |
| 1405 | const VarDecl *VD = cast<VarDecl>(Val: Elem.D); |
| 1406 | SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::note_local_var_initializer) |
| 1407 | << VD->getType()->isReferenceType() << VD->isImplicit() |
| 1408 | << VD->getDeclName() << nextPathEntryRange(Path, I: I + 1, E: L); |
| 1409 | break; |
| 1410 | } |
| 1411 | |
| 1412 | case IndirectLocalPathEntry::LambdaCaptureInit: { |
| 1413 | if (!Elem.Capture->capturesVariable()) |
| 1414 | break; |
| 1415 | // FIXME: We can't easily tell apart an init-capture from a nested |
| 1416 | // capture of an init-capture. |
| 1417 | const ValueDecl *VD = Elem.Capture->getCapturedVar(); |
| 1418 | SemaRef.Diag(Loc: Elem.Capture->getLocation(), |
| 1419 | DiagID: diag::note_lambda_capture_initializer) |
| 1420 | << VD << VD->isInitCapture() << Elem.Capture->isExplicit() |
| 1421 | << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD |
| 1422 | << nextPathEntryRange(Path, I: I + 1, E: L); |
| 1423 | break; |
| 1424 | } |
| 1425 | |
| 1426 | case IndirectLocalPathEntry::DefaultArg: { |
| 1427 | const auto *DAE = cast<CXXDefaultArgExpr>(Val: Elem.E); |
| 1428 | const ParmVarDecl *Param = DAE->getParam(); |
| 1429 | SemaRef.Diag(Loc: Param->getDefaultArgRange().getBegin(), |
| 1430 | DiagID: diag::note_init_with_default_argument) |
| 1431 | << Param << nextPathEntryRange(Path, I: I + 1, E: L); |
| 1432 | break; |
| 1433 | } |
| 1434 | } |
| 1435 | } |
| 1436 | |
| 1437 | // We didn't lifetime-extend, so don't go any further; we don't need more |
| 1438 | // warnings or errors on inner temporaries within this one's initializer. |
| 1439 | return false; |
| 1440 | }; |
| 1441 | |
| 1442 | llvm::SmallVector<IndirectLocalPathEntry, 8> Path; |
| 1443 | switch (LK) { |
| 1444 | case LK_Assignment: { |
| 1445 | if (shouldRunGSLAssignmentAnalysis(SemaRef, Entity: *AEntity)) |
| 1446 | Path.push_back(Elt: {lifetimes::isAssignmentOperatorLifetimeBound( |
| 1447 | CMD: AEntity->AssignmentOperator) |
| 1448 | ? IndirectLocalPathEntry::LifetimeBoundCall |
| 1449 | : IndirectLocalPathEntry::GslPointerAssignment, |
| 1450 | Init}); |
| 1451 | break; |
| 1452 | } |
| 1453 | case LK_LifetimeCapture: { |
| 1454 | if (lifetimes::isPointerLikeType(QT: Init->getType())) |
| 1455 | Path.push_back(Elt: {IndirectLocalPathEntry::GslPointerInit, Init}); |
| 1456 | break; |
| 1457 | } |
| 1458 | default: |
| 1459 | break; |
| 1460 | } |
| 1461 | |
| 1462 | if (Init->isGLValue()) |
| 1463 | visitLocalsRetainedByReferenceBinding(Path, Init, RK: RK_ReferenceBinding, |
| 1464 | Visit: TemporaryVisitor); |
| 1465 | else |
| 1466 | visitLocalsRetainedByInitializer( |
| 1467 | Path, Init, Visit: TemporaryVisitor, |
| 1468 | // Don't revisit the sub inits for the initialization case. |
| 1469 | /*RevisitSubinits=*/!InitEntity); |
| 1470 | } |
| 1471 | |
| 1472 | void checkInitLifetime(Sema &SemaRef, const InitializedEntity &Entity, |
| 1473 | Expr *Init) { |
| 1474 | auto LTResult = getEntityLifetime(Entity: &Entity); |
| 1475 | LifetimeKind LK = LTResult.getInt(); |
| 1476 | const InitializedEntity *ExtendingEntity = LTResult.getPointer(); |
| 1477 | checkExprLifetimeImpl(SemaRef, InitEntity: &Entity, ExtendingEntity, LK, |
| 1478 | /*AEntity=*/nullptr, /*CapEntity=*/nullptr, Init); |
| 1479 | } |
| 1480 | |
| 1481 | void checkExprLifetimeMustTailArg(Sema &SemaRef, |
| 1482 | const InitializedEntity &Entity, Expr *Init) { |
| 1483 | checkExprLifetimeImpl(SemaRef, InitEntity: &Entity, ExtendingEntity: nullptr, LK: LK_MustTail, |
| 1484 | /*AEntity=*/nullptr, /*CapEntity=*/nullptr, Init); |
| 1485 | } |
| 1486 | |
| 1487 | void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, |
| 1488 | Expr *Init) { |
| 1489 | bool EnableDanglingPointerAssignment = !SemaRef.getDiagnostics().isIgnored( |
| 1490 | DiagID: diag::warn_dangling_pointer_assignment, Loc: SourceLocation()); |
| 1491 | bool RunAnalysis = (EnableDanglingPointerAssignment && |
| 1492 | Entity.LHS->getType()->isPointerType()) || |
| 1493 | shouldRunGSLAssignmentAnalysis(SemaRef, Entity); |
| 1494 | |
| 1495 | if (!RunAnalysis) |
| 1496 | return; |
| 1497 | |
| 1498 | checkExprLifetimeImpl(SemaRef, /*InitEntity=*/nullptr, |
| 1499 | /*ExtendingEntity=*/nullptr, LK: LK_Assignment, AEntity: &Entity, |
| 1500 | /*CapEntity=*/nullptr, Init); |
| 1501 | } |
| 1502 | |
| 1503 | void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, |
| 1504 | Expr *Init) { |
| 1505 | if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_dangling_reference_captured, |
| 1506 | Loc: SourceLocation()) && |
| 1507 | SemaRef.getDiagnostics().isIgnored( |
| 1508 | DiagID: diag::warn_dangling_reference_captured_by_unknown, Loc: SourceLocation())) |
| 1509 | return; |
| 1510 | return checkExprLifetimeImpl(SemaRef, /*InitEntity=*/nullptr, |
| 1511 | /*ExtendingEntity=*/nullptr, LK: LK_LifetimeCapture, |
| 1512 | /*AEntity=*/nullptr, |
| 1513 | /*CapEntity=*/&Entity, Init); |
| 1514 | } |
| 1515 | |
| 1516 | } // namespace clang::sema |
| 1517 | |