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