1//===--- SemaLifetimeSafety.h - Sema support for lifetime safety =---------==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema-specific implementation for lifetime safety
10// analysis. It provides diagnostic reporting and helper functions that bridge
11// the lifetime safety analysis framework with Sema's diagnostic engine.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_LIB_SEMA_SEMALIFETIMESAFETY_H
16#define LLVM_CLANG_LIB_SEMA_SEMALIFETIMESAFETY_H
17
18#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
19#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h"
20#include "clang/Basic/DiagnosticSema.h"
21#include "clang/Lex/Lexer.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Sema/Sema.h"
24#include <string>
25
26namespace clang::lifetimes {
27
28inline bool ShouldCheckSafety(Sema &S, const Decl *D) {
29 DiagnosticsEngine &Diags = S.getDiagnostics();
30 constexpr unsigned DiagIDs[] = {
31 diag::warn_lifetime_safety_use_after_scope,
32 diag::warn_lifetime_safety_use_after_scope_moved,
33 diag::warn_lifetime_safety_use_after_free,
34 diag::warn_lifetime_safety_return_stack_addr,
35 diag::warn_lifetime_safety_return_stack_addr_moved,
36 diag::warn_lifetime_safety_invalidation,
37 diag::warn_lifetime_safety_dangling_field,
38 diag::warn_lifetime_safety_dangling_field_moved,
39 diag::warn_lifetime_safety_dangling_field_lambda_capture,
40 diag::warn_lifetime_safety_dangling_global,
41 diag::warn_lifetime_safety_dangling_global_moved,
42 diag::warn_lifetime_safety_dangling_global_in_main,
43 diag::warn_lifetime_safety_invalidated_field,
44 diag::warn_lifetime_safety_invalidated_global};
45 for (unsigned DiagID : DiagIDs)
46 if (!Diags.isIgnored(DiagID, Loc: D->getBeginLoc()))
47 return true;
48 return false;
49}
50
51inline bool ShouldCheckNoescapeViolations(Sema &S, const Decl *D) {
52 return !S.getDiagnostics().isIgnored(
53 DiagID: diag::warn_lifetime_safety_noescape_escapes, Loc: D->getBeginLoc());
54}
55
56inline bool ShouldCheckLifetimeboundViolations(Sema &S, const Decl *D) {
57 return !S.getDiagnostics().isIgnored(
58 DiagID: diag::warn_lifetime_safety_lifetimebound_violation, Loc: D->getBeginLoc());
59}
60
61inline bool ShouldCheckCaptureByViolations(Sema &S, const Decl *D) {
62 return !S.getDiagnostics().isIgnored(
63 DiagID: diag::warn_lifetime_safety_capture_by_violation, Loc: D->getBeginLoc());
64}
65
66inline bool ShouldCheckMisplacedLifetimebound(Sema &S, const Decl *D) {
67 DiagnosticsEngine &Diags = S.getDiagnostics();
68 constexpr unsigned DiagIDs[] = {
69 diag::warn_lifetime_safety_cross_tu_misplaced_lifetimebound,
70 diag::warn_lifetime_safety_intra_tu_misplaced_lifetimebound};
71 for (unsigned DiagID : DiagIDs)
72 if (!Diags.isIgnored(DiagID, Loc: D->getBeginLoc()))
73 return true;
74 return false;
75}
76
77inline bool ShouldCheckInapplicableLifetimebound(Sema &S, const Decl *D) {
78 return !S.getDiagnostics().isIgnored(
79 DiagID: diag::warn_lifetime_safety_inapplicable_lifetimebound, Loc: D->getBeginLoc());
80}
81
82inline bool ShouldCheckFieldOriginEscape(Sema &S, const Decl *D) {
83 return !S.getDiagnostics().isIgnored(
84 DiagID: diag::warn_lifetime_safety_field_origin_escape, Loc: D->getBeginLoc());
85}
86
87inline bool ShouldCheckDestructorUses(Sema &S, const Decl *D) {
88 DiagnosticsEngine &Diags = S.getDiagnostics();
89 constexpr unsigned DiagIDs[] = {
90 diag::warn_lifetime_safety_destructor_use_after_scope,
91 diag::warn_lifetime_safety_destructor_use_after_invalidation};
92 for (unsigned DiagID : DiagIDs)
93 if (!Diags.isIgnored(DiagID, Loc: D->getBeginLoc()))
94 return true;
95 return false;
96}
97
98inline bool ShouldSuggestLifetimeAnnotations(Sema &S, const Decl *D) {
99 DiagnosticsEngine &Diags = S.getDiagnostics();
100 constexpr unsigned DiagIDs[] = {
101 diag::warn_lifetime_safety_intra_tu_param_suggestion,
102 diag::warn_lifetime_safety_cross_tu_param_suggestion,
103 diag::warn_lifetime_safety_intra_tu_ctor_param_suggestion,
104 diag::warn_lifetime_safety_cross_tu_ctor_param_suggestion,
105 diag::warn_lifetime_safety_intra_tu_this_suggestion,
106 diag::warn_lifetime_safety_cross_tu_this_suggestion};
107 for (unsigned DiagID : DiagIDs)
108 if (!Diags.isIgnored(DiagID, Loc: D->getBeginLoc()))
109 return true;
110 return false;
111}
112
113inline bool IsLifetimeSafetyEnabled(Sema &S, const Decl *D) {
114 // TODO: Enable ObjectiveC later when we know it's stable enough.
115 if (S.getLangOpts().ObjC)
116 return false;
117
118 // TODO: Default this flag to on in the future.
119 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().EnableLifetimeSafetyInC)
120 return false;
121
122 // Translation-unit mode: whole-program analysis runs once on TU.
123 // Individual function analysis is disabled when TU mode is enabled.
124 if (S.getLangOpts().EnableLifetimeSafetyTUAnalysis)
125 return isa<TranslationUnitDecl>(Val: D);
126
127 // Per-function mode: analysis runs on each function/method individually.
128 // Skip TU-level calls when per-function mode is enabled.
129 if (isa<TranslationUnitDecl>(Val: D))
130 return false;
131
132 // Enable per-function mode via debug flag or specific diagnostics.
133 if (S.getLangOpts().DebugRunLifetimeSafety)
134 return true;
135
136 return ShouldCheckSafety(S, D) || ShouldCheckNoescapeViolations(S, D) ||
137 ShouldCheckLifetimeboundViolations(S, D) ||
138 ShouldCheckCaptureByViolations(S, D) ||
139 ShouldCheckMisplacedLifetimebound(S, D) ||
140 ShouldCheckInapplicableLifetimebound(S, D) ||
141 ShouldCheckFieldOriginEscape(S, D) ||
142 ShouldCheckDestructorUses(S, D) ||
143 ShouldSuggestLifetimeAnnotations(S, D);
144}
145
146inline LifetimeSafetyOpts GetLifetimeSafetyOpts(Sema &S, const Decl *D) {
147 LifetimeSafetyOpts LSOpts;
148 LSOpts.MaxCFGBlocks = S.getLangOpts().LifetimeSafetyMaxCFGBlocks;
149 LSOpts.SuggestAnnotations = ShouldSuggestLifetimeAnnotations(S, D);
150 LSOpts.CheckNoescapeViolations = ShouldCheckNoescapeViolations(S, D);
151 LSOpts.CheckLifetimeboundViolations =
152 ShouldCheckLifetimeboundViolations(S, D);
153 LSOpts.CheckMisplacedLifetimebound = ShouldCheckMisplacedLifetimebound(S, D);
154 LSOpts.CheckInapplicableLifetimebound =
155 ShouldCheckInapplicableLifetimebound(S, D);
156 LSOpts.CheckFieldOriginEscape = ShouldCheckFieldOriginEscape(S, D);
157 LSOpts.CheckDestructorUses = ShouldCheckDestructorUses(S, D);
158 LSOpts.CheckCaptureByViolations = ShouldCheckCaptureByViolations(S, D);
159 return LSOpts;
160}
161
162class LifetimeSafetySemaHelperImpl final : public LifetimeSafetySemaHelper {
163
164public:
165 LifetimeSafetySemaHelperImpl(Sema &S) : S(S) {}
166
167 void reportUseAfterScope(const Expr *IssueExpr, const UseSite &Use,
168 const Expr *MovedExpr, SourceLocation FreeLoc,
169 llvm::ArrayRef<const Expr *> ExprChain) override {
170 unsigned DiagID;
171 if (Use.getKind() == UseKind::Destructor)
172 DiagID = diag::warn_lifetime_safety_destructor_use_after_scope;
173 else
174 DiagID = MovedExpr ? diag::warn_lifetime_safety_use_after_scope_moved
175 : diag::warn_lifetime_safety_use_after_scope;
176 std::string DestroyedSubject = getDiagSubjectDescription(E: IssueExpr);
177
178 S.Diag(Loc: IssueExpr->getExprLoc(), DiagID)
179 << DestroyedSubject << IssueExpr->getSourceRange();
180 if (MovedExpr)
181 S.Diag(Loc: MovedExpr->getExprLoc(), DiagID: diag::note_lifetime_safety_moved_here)
182 << MovedExpr->getSourceRange();
183 S.Diag(Loc: FreeLoc, DiagID: diag::note_lifetime_safety_destroyed_here)
184 << DestroyedSubject;
185 reportAliasingChain(OriginExprChain: ExprChain);
186 reportUseNote(Use);
187 }
188
189 void reportUseAfterReturn(const Expr *IssueExpr, const Expr *ReturnExpr,
190 const Expr *MovedExpr,
191 llvm::ArrayRef<const Expr *> ExprChain) override {
192 unsigned DiagID = MovedExpr
193 ? diag::warn_lifetime_safety_return_stack_addr_moved
194 : diag::warn_lifetime_safety_return_stack_addr;
195
196 S.Diag(Loc: IssueExpr->getExprLoc(), DiagID)
197 << getDiagSubjectDescription(E: IssueExpr) << IssueExpr->getSourceRange();
198
199 if (MovedExpr)
200 S.Diag(Loc: MovedExpr->getExprLoc(), DiagID: diag::note_lifetime_safety_moved_here)
201 << MovedExpr->getSourceRange();
202 reportAliasingChain(OriginExprChain: ExprChain);
203 S.Diag(Loc: ReturnExpr->getExprLoc(), DiagID: diag::note_lifetime_safety_returned_here)
204 << ReturnExpr->getSourceRange();
205 }
206
207 void reportDanglingField(const Expr *IssueExpr,
208 const FieldDecl *DanglingField,
209 const Expr *MovedExpr, bool IsCapturedByLambda,
210 SourceLocation ExpiryLoc,
211 llvm::ArrayRef<const Expr *> ExprChain) override {
212 unsigned DiagID =
213 IsCapturedByLambda
214 ? diag::warn_lifetime_safety_dangling_field_lambda_capture
215 : (MovedExpr ? diag::warn_lifetime_safety_dangling_field_moved
216 : diag::warn_lifetime_safety_dangling_field);
217
218 S.Diag(Loc: IssueExpr->getExprLoc(), DiagID)
219 << getDiagSubjectDescription(E: IssueExpr)
220 << getDiagSubjectDescription(VD: DanglingField)
221 << IssueExpr->getSourceRange();
222 if (MovedExpr)
223 S.Diag(Loc: MovedExpr->getExprLoc(), DiagID: diag::note_lifetime_safety_moved_here)
224 << MovedExpr->getSourceRange();
225 reportAliasingChain(OriginExprChain: ExprChain);
226 S.Diag(Loc: DanglingField->getLocation(),
227 DiagID: diag::note_lifetime_safety_dangling_field_here)
228 << DanglingField->getEndLoc();
229 }
230
231 void reportDanglingGlobal(const Expr *IssueExpr,
232 const VarDecl *DanglingGlobal,
233 const Expr *MovedExpr, SourceLocation ExpiryLoc,
234 llvm::ArrayRef<const Expr *> ExprChain,
235 bool IsMain = false) override {
236 unsigned DiagID;
237 if (IsMain) {
238 DiagID = MovedExpr ? diag::warn_lifetime_safety_dangling_global_moved
239 : diag::warn_lifetime_safety_dangling_global_in_main;
240 } else {
241 DiagID = MovedExpr ? diag::warn_lifetime_safety_dangling_global_moved
242 : diag::warn_lifetime_safety_dangling_global;
243 }
244
245 S.Diag(Loc: IssueExpr->getExprLoc(), DiagID)
246 << getDiagSubjectDescription(E: IssueExpr)
247 << getDiagSubjectDescription(VD: DanglingGlobal)
248 << IssueExpr->getSourceRange();
249 if (MovedExpr)
250 S.Diag(Loc: MovedExpr->getExprLoc(), DiagID: diag::note_lifetime_safety_moved_here)
251 << MovedExpr->getSourceRange();
252 reportAliasingChain(OriginExprChain: ExprChain);
253 if (DanglingGlobal->isStaticLocal() || DanglingGlobal->isStaticDataMember())
254 S.Diag(Loc: DanglingGlobal->getLocation(),
255 DiagID: diag::note_lifetime_safety_dangling_static_here)
256 << DanglingGlobal->getEndLoc();
257 else
258 S.Diag(Loc: DanglingGlobal->getLocation(),
259 DiagID: diag::note_lifetime_safety_dangling_global_here)
260 << DanglingGlobal->getEndLoc();
261 }
262
263 void
264 reportUseAfterInvalidation(const Expr *IssueExpr, const UseSite &Use,
265 const Expr *InvalidationExpr,
266 llvm::ArrayRef<const Expr *> ExprChain) override {
267 reportUseAfterInvalidationImpl(
268 IssueLoc: IssueExpr->getExprLoc(), IssueRange: IssueExpr->getSourceRange(),
269 InvalidatedSubject: getDiagSubjectDescription(E: IssueExpr), InvalidationExpr, ExprChain, Use);
270 }
271 void
272 reportUseAfterInvalidation(const ParmVarDecl *PVD, const UseSite &Use,
273 const Expr *InvalidationExpr,
274 llvm::ArrayRef<const Expr *> ExprChain) override {
275 reportUseAfterInvalidationImpl(
276 IssueLoc: PVD->getSourceRange().getBegin(), IssueRange: PVD->getSourceRange(),
277 InvalidatedSubject: getDiagSubjectDescription(VD: PVD), InvalidationExpr, ExprChain, Use);
278 }
279
280 void reportInvalidatedField(const Expr *IssueExpr,
281 const FieldDecl *DanglingField,
282 const Expr *InvalidationExpr,
283 llvm::ArrayRef<const Expr *> ExprChain) override {
284 std::string InvalidatedSubject = getDiagSubjectDescription(E: IssueExpr);
285 S.Diag(Loc: IssueExpr->getExprLoc(),
286 DiagID: diag::warn_lifetime_safety_invalidated_field)
287 << InvalidatedSubject << getDiagSubjectDescription(VD: DanglingField)
288 << IssueExpr->getSourceRange();
289 reportInvalidationSite(InvalidationExpr, InvalidatedSubject);
290 reportAliasingChain(OriginExprChain: ExprChain);
291 S.Diag(Loc: DanglingField->getLocation(),
292 DiagID: diag::note_lifetime_safety_dangling_field_here)
293 << DanglingField->getEndLoc();
294 }
295
296 void reportInvalidatedField(const ParmVarDecl *PVD,
297 const FieldDecl *DanglingField,
298 const Expr *InvalidationExpr,
299 llvm::ArrayRef<const Expr *> ExprChain) override {
300 std::string InvalidatedSubject = getDiagSubjectDescription(VD: PVD);
301 S.Diag(Loc: PVD->getSourceRange().getBegin(),
302 DiagID: diag::warn_lifetime_safety_invalidated_field)
303 << InvalidatedSubject << getDiagSubjectDescription(VD: DanglingField)
304 << PVD->getSourceRange();
305 reportInvalidationSite(InvalidationExpr, InvalidatedSubject);
306 reportAliasingChain(OriginExprChain: ExprChain);
307 S.Diag(Loc: DanglingField->getLocation(),
308 DiagID: diag::note_lifetime_safety_dangling_field_here)
309 << DanglingField->getEndLoc();
310 }
311
312 void
313 reportInvalidatedGlobal(const Expr *IssueExpr, const VarDecl *DanglingGlobal,
314 const Expr *InvalidationExpr,
315 llvm::ArrayRef<const Expr *> ExprChain) override {
316 std::string InvalidatedSubject = getDiagSubjectDescription(E: IssueExpr);
317 S.Diag(Loc: IssueExpr->getExprLoc(),
318 DiagID: diag::warn_lifetime_safety_invalidated_global)
319 << InvalidatedSubject << getDiagSubjectDescription(VD: DanglingGlobal)
320 << IssueExpr->getSourceRange();
321 reportInvalidationSite(InvalidationExpr, InvalidatedSubject);
322 reportAliasingChain(OriginExprChain: ExprChain);
323 if (DanglingGlobal->isStaticLocal() || DanglingGlobal->isStaticDataMember())
324 S.Diag(Loc: DanglingGlobal->getLocation(),
325 DiagID: diag::note_lifetime_safety_dangling_static_here)
326 << DanglingGlobal->getEndLoc();
327 else
328 S.Diag(Loc: DanglingGlobal->getLocation(),
329 DiagID: diag::note_lifetime_safety_dangling_global_here)
330 << DanglingGlobal->getEndLoc();
331 }
332
333 void
334 reportInvalidatedGlobal(const ParmVarDecl *PVD, const VarDecl *DanglingGlobal,
335 const Expr *InvalidationExpr,
336 llvm::ArrayRef<const Expr *> ExprChain) override {
337 std::string InvalidatedSubject = getDiagSubjectDescription(VD: PVD);
338 S.Diag(Loc: PVD->getSourceRange().getBegin(),
339 DiagID: diag::warn_lifetime_safety_invalidated_global)
340 << InvalidatedSubject << getDiagSubjectDescription(VD: DanglingGlobal)
341 << PVD->getSourceRange();
342 reportInvalidationSite(InvalidationExpr, InvalidatedSubject);
343 reportAliasingChain(OriginExprChain: ExprChain);
344 if (DanglingGlobal->isStaticLocal() || DanglingGlobal->isStaticDataMember())
345 S.Diag(Loc: DanglingGlobal->getLocation(),
346 DiagID: diag::note_lifetime_safety_dangling_static_here)
347 << DanglingGlobal->getEndLoc();
348 else
349 S.Diag(Loc: DanglingGlobal->getLocation(),
350 DiagID: diag::note_lifetime_safety_dangling_global_here)
351 << DanglingGlobal->getEndLoc();
352 }
353
354 void suggestLifetimeboundToParmVar(WarningScope Scope,
355 const ParmVarDecl *ParmToAnnotate,
356 EscapingTarget Target) override {
357 unsigned DiagID;
358 if (isa<CXXConstructorDecl>(Val: ParmToAnnotate->getDeclContext()))
359 DiagID = (Scope == WarningScope::CrossTU)
360 ? diag::warn_lifetime_safety_cross_tu_ctor_param_suggestion
361 : diag::warn_lifetime_safety_intra_tu_ctor_param_suggestion;
362 else
363 DiagID = (Scope == WarningScope::CrossTU)
364 ? diag::warn_lifetime_safety_cross_tu_param_suggestion
365 : diag::warn_lifetime_safety_intra_tu_param_suggestion;
366
367 auto [InsertionPoint, FixItText] = getLifetimeBoundFixIt(Decl: ParmToAnnotate);
368
369 S.Diag(Loc: InsertionPoint, DiagID)
370 << ParmToAnnotate->getSourceRange()
371 << FixItHint::CreateInsertion(InsertionLoc: InsertionPoint, Code: FixItText);
372
373 if (const auto *EscapeExpr = dyn_cast<const Expr *>(Val&: Target))
374 S.Diag(Loc: EscapeExpr->getBeginLoc(),
375 DiagID: diag::note_lifetime_safety_suggestion_returned_here)
376 << EscapeExpr->getSourceRange();
377 else if (const auto *EscapeField = dyn_cast<const FieldDecl *>(Val&: Target))
378 S.Diag(Loc: EscapeField->getLocation(),
379 DiagID: diag::note_lifetime_safety_escapes_to_field_here)
380 << EscapeField->getSourceRange();
381 }
382
383 void reportLifetimeboundViolation(
384 const ParmVarDecl *ParmWithLifetimebound) override {
385 const auto *Attr = ParmWithLifetimebound->getAttr<LifetimeBoundAttr>();
386 StringRef ParamName = ParmWithLifetimebound->getName();
387 bool HasName = ParamName.size() > 0;
388 S.Diag(Loc: Attr->getLocation(),
389 DiagID: diag::warn_lifetime_safety_lifetimebound_violation)
390 << HasName << ParamName << Attr->getRange();
391 }
392
393 void reportLifetimeboundViolation(
394 const CXXMethodDecl *MDWithLifetimebound) override {
395 const auto *Attr =
396 getImplicitObjectParamLifetimeBoundAttr(FD: MDWithLifetimebound);
397 assert(Attr && "Expected lifetimebound attribute");
398 S.Diag(Loc: Attr->getLocation(),
399 DiagID: diag::warn_lifetime_safety_lifetimebound_violation)
400 << 2 << "" << Attr->getRange();
401 }
402
403 /// Returns the name of \p CapturingParam on the declaration where \p Attr of
404 /// \p PVD is written, as the attribute's parameter names refer to that
405 /// declaration.
406 static StringRef getCapturerName(const ParmVarDecl *PVD,
407 const LifetimeCaptureByAttr *Attr,
408 const ParmVarDecl *CapturingParam) {
409 if (!CapturingParam)
410 return "";
411 const auto *Fn = cast<FunctionDecl>(Val: PVD->getDeclContext());
412 for (const FunctionDecl *Redecl : Fn->redecls()) {
413 const ParmVarDecl *P = Redecl->getParamDecl(i: PVD->getFunctionScopeIndex());
414 if (llvm::any_of(Range: P->specific_attrs<LifetimeCaptureByAttr>(),
415 P: [&](const LifetimeCaptureByAttr *A) {
416 return !A->isInherited() &&
417 A->getLocation() == Attr->getLocation();
418 })) {
419 StringRef Name =
420 Redecl->getParamDecl(i: CapturingParam->getFunctionScopeIndex())
421 ->getName();
422 if (!Name.empty())
423 return Name;
424 break;
425 }
426 }
427 return CapturingParam->getName();
428 }
429
430 void reportCaptureByViolation(const ParmVarDecl *PVD,
431 const LifetimeCaptureByAttr *Attr,
432 int CapturerIdx,
433 const ValueDecl *CapturedBy) override {
434 assert(!Attr->isImplicit() && "only written attributes are verified");
435 const auto *CapturingParam = dyn_cast_if_present<ParmVarDecl>(Val: CapturedBy);
436 assert((CapturingParam || CapturerIdx == LifetimeCaptureByAttr::This ||
437 CapturerIdx == LifetimeCaptureByAttr::Global) &&
438 "only this, global and parameter capturers are verified");
439 // The capturer kinds of warn_lifetime_safety_capture_by_violation.
440 enum CapturerKind { CapturedByThis, CapturedByGlobal, CapturedByParam };
441 CapturerKind Kind = CapturedByThis;
442 if (CapturingParam)
443 Kind = CapturedByParam;
444 else if (CapturerIdx == LifetimeCaptureByAttr::Global)
445 Kind = CapturedByGlobal;
446 S.Diag(Loc: Attr->getLocation(), DiagID: diag::warn_lifetime_safety_capture_by_violation)
447 << PVD << Kind << getCapturerName(PVD, Attr, CapturingParam)
448 << Attr->getRange();
449 if (!CapturedBy)
450 return;
451 unsigned NoteID = diag::note_lifetime_safety_escapes_to_global_here;
452 if (CapturingParam)
453 NoteID = diag::note_lifetime_safety_escapes_to_param_here;
454 else if (isa<FieldDecl>(Val: CapturedBy))
455 NoteID = diag::note_lifetime_safety_escapes_to_field_here;
456 else if (const auto *VD = cast<VarDecl>(Val: CapturedBy);
457 VD->isStaticLocal() || VD->isStaticDataMember())
458 NoteID = diag::note_lifetime_safety_escapes_to_static_storage_here;
459 S.Diag(Loc: CapturedBy->getLocation(), DiagID: NoteID) << CapturedBy->getEndLoc();
460 }
461
462 void reportMisplacedLifetimebound(WarningScope Scope,
463 const CXXMethodDecl *FDef,
464 const CXXMethodDecl *FDecl) override {
465 const auto *Attr = getDirectImplicitObjectLifetimeBoundAttr(FD: FDef);
466 assert(Attr && "Expected lifetimebound attribute");
467 unsigned DiagID =
468 Scope == WarningScope::CrossTU
469 ? diag::warn_lifetime_safety_cross_tu_misplaced_lifetimebound
470 : diag::warn_lifetime_safety_intra_tu_misplaced_lifetimebound;
471
472 auto [InsertionPoint, FixItText] = getLifetimeBoundFixIt(MD: FDecl);
473
474 // Do not emit fix-its in macros or at invalid locations.
475 bool IsMacro =
476 FDecl->getBeginLoc().isMacroID() || InsertionPoint.isMacroID();
477
478 if (IsMacro || InsertionPoint.isInvalid())
479 S.Diag(Loc: FDecl->getLocation(), DiagID);
480 else
481 S.Diag(Loc: InsertionPoint, DiagID)
482 << FixItHint::CreateInsertion(InsertionLoc: InsertionPoint, Code: FixItText);
483
484 S.Diag(Loc: Attr->getLocation(), DiagID: diag::note_lifetime_safety_lifetimebound_here)
485 << Attr->getRange();
486 }
487
488 void reportMisplacedLifetimebound(WarningScope Scope,
489 const ParmVarDecl *PVDDef,
490 const ParmVarDecl *PVDDecl) override {
491
492 const auto *Attr = PVDDef->getAttr<LifetimeBoundAttr>();
493 assert(Attr && "Expected lifetimebound attribute");
494 unsigned DiagID =
495 Scope == WarningScope::CrossTU
496 ? diag::warn_lifetime_safety_cross_tu_misplaced_lifetimebound
497 : diag::warn_lifetime_safety_intra_tu_misplaced_lifetimebound;
498
499 auto [InsertionPoint, FixItText] = getLifetimeBoundFixIt(Decl: PVDDecl);
500
501 // Do not emit fix-its in macros or at invalid locations.
502 bool IsMacro =
503 PVDDecl->getBeginLoc().isMacroID() || InsertionPoint.isMacroID();
504
505 if (IsMacro || InsertionPoint.isInvalid())
506 S.Diag(Loc: PVDDecl->getBeginLoc(), DiagID) << PVDDecl->getSourceRange();
507 else
508 S.Diag(Loc: InsertionPoint, DiagID)
509 << PVDDecl->getSourceRange()
510 << FixItHint::CreateInsertion(InsertionLoc: InsertionPoint, Code: FixItText);
511
512 S.Diag(Loc: Attr->getLocation(), DiagID: diag::note_lifetime_safety_lifetimebound_here)
513 << Attr->getRange();
514 }
515
516 void reportInapplicableLifetimebound(const ParmVarDecl *PVD) override {
517 assert(PVD->hasAttr<LifetimeBoundAttr>() &&
518 "Expected parameter to have lifetimebound attribute");
519 const auto *Attr = PVD->getAttr<LifetimeBoundAttr>();
520 S.Diag(Loc: Attr->getLocation(),
521 DiagID: diag::warn_lifetime_safety_inapplicable_lifetimebound)
522 << PVD->getType() << Attr->getRange();
523 }
524
525 void suggestLifetimeboundToImplicitThis(WarningScope Scope,
526 const CXXMethodDecl *MD,
527 const Expr *EscapeExpr) override {
528 unsigned DiagID = (Scope == WarningScope::CrossTU)
529 ? diag::warn_lifetime_safety_cross_tu_this_suggestion
530 : diag::warn_lifetime_safety_intra_tu_this_suggestion;
531
532 auto [InsertionPoint, FixItText] = getLifetimeBoundFixIt(MD);
533
534 S.Diag(Loc: InsertionPoint, DiagID)
535 << MD->getNameInfo().getSourceRange()
536 << FixItHint::CreateInsertion(InsertionLoc: InsertionPoint, Code: FixItText);
537
538 S.Diag(Loc: EscapeExpr->getBeginLoc(),
539 DiagID: diag::note_lifetime_safety_suggestion_returned_here)
540 << EscapeExpr->getSourceRange();
541 }
542
543 void reportFieldOriginEscape(const CXXMethodDecl *MD, const FieldDecl *FD,
544 const Expr *EscapeExpr) override {
545 std::string FieldDesc = getDiagSubjectDescription(VD: FD);
546 S.Diag(Loc: MD->getLocation(), DiagID: diag::warn_lifetime_safety_field_origin_escape)
547 << FieldDesc << MD->getNameInfo().getSourceRange();
548
549 S.Diag(Loc: EscapeExpr->getBeginLoc(), DiagID: diag::note_lifetime_safety_returned_here)
550 << EscapeExpr->getSourceRange();
551
552 // A raw pointer field may own its storage (e.g., Vector::data()).
553 if (FD->getType()->isPointerType())
554 S.Diag(Loc: FD->getLocation(),
555 DiagID: diag::note_lifetime_safety_owned_field_suggestion)
556 << FieldDesc << FD->getSourceRange();
557 }
558
559 void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
560 const Expr *EscapeExpr) override {
561 S.Diag(Loc: ParmWithNoescape->getBeginLoc(),
562 DiagID: diag::warn_lifetime_safety_noescape_escapes)
563 << ParmWithNoescape->getSourceRange();
564
565 S.Diag(Loc: EscapeExpr->getBeginLoc(),
566 DiagID: diag::note_lifetime_safety_suggestion_returned_here)
567 << EscapeExpr->getSourceRange();
568 }
569
570 void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
571 const FieldDecl *EscapeField) override {
572 S.Diag(Loc: ParmWithNoescape->getBeginLoc(),
573 DiagID: diag::warn_lifetime_safety_noescape_escapes)
574 << ParmWithNoescape->getSourceRange();
575
576 S.Diag(Loc: EscapeField->getLocation(),
577 DiagID: diag::note_lifetime_safety_escapes_to_field_here)
578 << EscapeField->getEndLoc();
579 }
580
581 void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
582 const VarDecl *EscapeGlobal) override {
583 S.Diag(Loc: ParmWithNoescape->getBeginLoc(),
584 DiagID: diag::warn_lifetime_safety_noescape_escapes)
585 << ParmWithNoescape->getSourceRange();
586 if (EscapeGlobal->isStaticLocal() || EscapeGlobal->isStaticDataMember())
587 S.Diag(Loc: EscapeGlobal->getLocation(),
588 DiagID: diag::note_lifetime_safety_escapes_to_static_storage_here)
589 << EscapeGlobal->getEndLoc();
590 else
591 S.Diag(Loc: EscapeGlobal->getLocation(),
592 DiagID: diag::note_lifetime_safety_escapes_to_global_here)
593 << EscapeGlobal->getEndLoc();
594 }
595
596 void addLifetimeBoundToImplicitThis(const CXXMethodDecl *MD) override {
597 S.addLifetimeBoundToImplicitThis(MD: const_cast<CXXMethodDecl *>(MD));
598 }
599
600private:
601 // Returns true if the expression frees memory: a `delete` expression or a
602 // call to a freeing function (e.g. annotated with `ownership_takes`).
603 static bool isFreeingExpr(const Expr *InvalidationExpr) {
604 if (isa<CXXDeleteExpr>(Val: InvalidationExpr))
605 return true;
606 const FunctionDecl *FD = FunctionCallInfo(InvalidationExpr).FD;
607 return FD && isFreeingFunction(FD: *FD);
608 }
609
610 struct LifetimeBoundMacroCache {
611 bool IsBuilt = false;
612 SmallVector<const IdentifierInfo *> Candidates;
613 };
614
615 void buildLifetimeBoundMacroCache(LifetimeBoundMacroCache &Cache,
616 ArrayRef<TokenValue> Tokens) {
617 if (Cache.IsBuilt)
618 return;
619
620 const Preprocessor &PP = S.getPreprocessor();
621 // Collect macro names that were ever defined as a lifetimebound attribute.
622 for (const auto &M : PP.macros()) {
623 const IdentifierInfo *II = M.first;
624 const MacroDirective *MD = PP.getLocalMacroDirectiveHistory(II);
625 if (!MD)
626 continue;
627
628 // Include earlier matching definitions to handle redefinitions.
629 for (MacroDirective::DefInfo Def = MD->getDefinition(); Def;
630 Def = Def.getPreviousDefinition()) {
631 const MacroInfo *MI = Def.getMacroInfo();
632 if (MI->isObjectLike() && Tokens.size() == MI->getNumTokens() &&
633 std::equal(first1: Tokens.begin(), last1: Tokens.end(), first2: MI->tokens_begin())) {
634 Cache.Candidates.push_back(Elt: II);
635 break;
636 }
637 }
638 }
639 Cache.IsBuilt = true;
640 }
641
642 StringRef getLastCachedMacroWithSpelling(SourceLocation Loc,
643 llvm::ArrayRef<TokenValue> Tokens,
644 LifetimeBoundMacroCache &Cache) {
645 if (Loc.isInvalid())
646 return {};
647
648 buildLifetimeBoundMacroCache(Cache, Tokens);
649
650 const Preprocessor &PP = S.getPreprocessor();
651 const SourceManager &SM = S.getSourceManager();
652 SourceLocation BestLocation;
653 StringRef BestSpelling;
654 for (const IdentifierInfo *II : Cache.Candidates) {
655 const MacroDirective *MD = PP.getLocalMacroDirectiveHistory(II);
656 const MacroDirective::DefInfo Def = MD->findDirectiveAtLoc(L: Loc, SM);
657 if (!Def || !Def.getMacroInfo())
658 continue;
659
660 // Ensure the macro definition active at Loc still has this spelling.
661 const MacroInfo *MI = Def.getMacroInfo();
662 if (!MI->isObjectLike() || Tokens.size() != MI->getNumTokens() ||
663 !std::equal(first1: Tokens.begin(), last1: Tokens.end(), first2: MI->tokens_begin()))
664 continue;
665
666 // Choose the matching macro defined latest before Loc.
667 SourceLocation Location = Def.getLocation();
668 assert(Location.isInvalid() ||
669 SM.isBeforeInTranslationUnit(Location, Loc));
670 if (BestLocation.isInvalid() ||
671 (Location.isValid() &&
672 SM.isBeforeInTranslationUnit(LHS: BestLocation, RHS: Location))) {
673 BestLocation = Location;
674 BestSpelling = II->getName();
675 }
676 }
677 return BestSpelling;
678 }
679
680 void reportInvalidationSite(const Expr *InvalidationExpr,
681 StringRef InvalidatedSubject) {
682 auto Diag = isFreeingExpr(InvalidationExpr)
683 ? diag::note_lifetime_safety_freed_here
684 : diag::note_lifetime_safety_invalidated_here;
685 S.Diag(Loc: InvalidationExpr->getExprLoc(), DiagID: Diag)
686 << InvalidatedSubject << InvalidationExpr->getSourceRange();
687 }
688
689 void reportUseAfterInvalidationImpl(SourceLocation IssueLoc,
690 SourceRange IssueRange,
691 StringRef InvalidatedSubject,
692 const Expr *InvalidationExpr,
693 llvm::ArrayRef<const Expr *> ExprChain,
694 const UseSite &Use) {
695 S.Diag(Loc: IssueLoc, DiagID: getInvalidationWarnDiag(IsFree: isFreeingExpr(InvalidationExpr),
696 Kind: Use.getKind()))
697 << InvalidatedSubject << IssueRange;
698 reportInvalidationSite(InvalidationExpr, InvalidatedSubject);
699 reportAliasingChain(OriginExprChain: ExprChain);
700 reportUseNote(Use);
701 }
702
703 static unsigned getInvalidationWarnDiag(bool IsFree, UseKind Kind) {
704 if (Kind == UseKind::Destructor)
705 return IsFree
706 ? diag::warn_lifetime_safety_destructor_use_after_scope
707 : diag::warn_lifetime_safety_destructor_use_after_invalidation;
708 return IsFree ? diag::warn_lifetime_safety_use_after_free
709 : diag::warn_lifetime_safety_invalidation;
710 }
711
712 void reportUseNote(const UseSite &Use) {
713 switch (Use.getKind()) {
714 case UseKind::Explicit:
715 S.Diag(Loc: Use.getLoc(), DiagID: diag::note_lifetime_safety_used_here)
716 << Use.getRange();
717 return;
718 case UseKind::Destructor:
719 S.Diag(Loc: Use.getLoc(), DiagID: diag::note_lifetime_safety_used_by_destructor)
720 << Use.getScopeExitVD();
721 return;
722 case UseKind::Cleanup:
723 S.Diag(Loc: Use.getLoc(), DiagID: diag::note_lifetime_safety_used_by_cleanup)
724 << Use.getScopeExitVD();
725 return;
726 }
727 llvm_unreachable("unknown UseKind");
728 }
729
730 std::string getLifetimeBoundFixItText(SourceLocation Loc, bool LeadingSpace,
731 bool AllowGNUAttrMacro = true) {
732 const bool UseCXX11AttrSpelling =
733 S.getLangOpts().CPlusPlus || S.getLangOpts().C23;
734 const StringRef Fallback = UseCXX11AttrSpelling
735 ? "[[clang::lifetimebound]]"
736 : "__attribute__((lifetimebound))";
737 StringRef Spelling = S.getLangOpts().LifetimeSafetyLifetimeBoundMacro;
738 if (Spelling.empty() && Loc.isValid()) {
739 const Preprocessor &PP = S.getPreprocessor();
740 if (UseCXX11AttrSpelling)
741 Spelling = getLastCachedMacroWithSpelling(
742 Loc,
743 Tokens: {tok::l_square, tok::l_square, PP.getIdentifierInfo(Name: "clang"),
744 tok::coloncolon, PP.getIdentifierInfo(Name: "lifetimebound"),
745 tok::r_square, tok::r_square},
746 Cache&: ClangLifetimeBoundMacroCache);
747
748 if (Spelling.empty() && AllowGNUAttrMacro)
749 Spelling = getLastCachedMacroWithSpelling(
750 Loc,
751 Tokens: {tok::kw___attribute, tok::l_paren, tok::l_paren,
752 PP.getIdentifierInfo(Name: "lifetimebound"), tok::r_paren, tok::r_paren},
753 Cache&: GNULifetimeBoundMacroCache);
754 }
755 const std::string Text = Spelling.empty() ? Fallback.str() : Spelling.str();
756 return LeadingSpace ? " " + Text : Text + " ";
757 }
758
759 std::pair<SourceLocation, std::string>
760 getLifetimeBoundFixIt(const ParmVarDecl *Decl) {
761 SourceLocation InsertionPoint = Lexer::getLocForEndOfToken(
762 Loc: Decl->getEndLoc(), Offset: 0, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
763 bool LeadingSpace = true;
764
765 if (!Decl->getIdentifier()) {
766 // For unnamed parameters, placing attributes after the type would be
767 // parsed as a type attribute, not a parameter attribute.
768 InsertionPoint = Decl->getBeginLoc();
769 LeadingSpace = false;
770 } else if (Decl->hasDefaultArg()) {
771 // If the parameter has a default argument, place the attribute after the
772 // named argument.
773 InsertionPoint = Lexer::getLocForEndOfToken(
774 Loc: Decl->getLocation(), Offset: 0, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
775 }
776 return {InsertionPoint,
777 getLifetimeBoundFixItText(Loc: InsertionPoint, LeadingSpace)};
778 }
779
780 std::pair<SourceLocation, std::string>
781 getLifetimeBoundFixIt(const CXXMethodDecl *MD) {
782 const auto MDL = MD->getTypeSourceInfo()->getTypeLoc();
783 SourceLocation InsertionPoint = Lexer::getLocForEndOfToken(
784 Loc: MDL.getEndLoc(), Offset: 0, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
785
786 if (const auto *FPT = MD->getType()->getAs<FunctionProtoType>();
787 FPT && FPT->hasTrailingReturn()) {
788 // For trailing return types, 'getEndLoc()' includes the return type
789 // after '->', placing the attribute in an invalid position.
790 // Instead use 'getLocalRangeEnd()' which gives the '->' location
791 // for trailing returns, so find the last token before it.
792 const auto FTL = MDL.getAs<FunctionTypeLoc>();
793 assert(FTL);
794 InsertionPoint = Lexer::getLocForEndOfToken(
795 Loc: Lexer::findPreviousToken(Loc: FTL.getLocalRangeEnd(), SM: S.getSourceManager(),
796 LangOpts: S.getLangOpts(),
797 /*IncludeComments=*/IncludeComments: false)
798 ->getLocation(),
799 Offset: 0, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
800 }
801 return {InsertionPoint,
802 getLifetimeBoundFixItText(Loc: InsertionPoint, /*LeadingSpace=*/LeadingSpace: true,
803 /*AllowGNUAttrMacro=*/AllowGNUAttrMacro: false)};
804 }
805
806 std::string getDiagSubjectDescription(const ValueDecl *VD) {
807 std::string Res;
808 llvm::raw_string_ostream OS(Res);
809 if (isa<FieldDecl>(Val: VD)) {
810 OS << "field";
811 } else if (isa<ParmVarDecl>(Val: VD)) {
812 OS << "parameter";
813 } else if (const auto *Var = dyn_cast<VarDecl>(Val: VD)) {
814 if (Var->isStaticLocal() || Var->isStaticDataMember())
815 OS << "static variable";
816 else if (Var->hasGlobalStorage())
817 OS << "global variable";
818 else
819 OS << "local variable";
820 } else {
821 OS << "variable";
822 }
823 OS << " '";
824 VD->getNameForDiagnostic(OS, Policy: S.getPrintingPolicy(), /*Qualified=*/Qualified: false);
825 OS << "'";
826 return Res;
827 }
828
829 std::string getDiagSubjectDescription(const Expr *E) {
830 E = ignoreParensAndImpCasts(E);
831 if (const auto *DAE = dyn_cast<CXXDefaultArgExpr>(Val: E))
832 return getDiagSubjectDescription(E: DAE->getExpr()->IgnoreParenBaseCasts());
833 if (isa<MaterializeTemporaryExpr>(Val: E))
834 return "temporary object";
835 if (isa<CXXNewExpr>(Val: E))
836 return "allocated object";
837 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
838 return getDiagSubjectDescription(VD: DRE->getDecl());
839 if (const auto *ME = dyn_cast<MemberExpr>(Val: E))
840 if (const auto *VD = dyn_cast<VarDecl>(Val: ME->getMemberDecl()))
841 return getDiagSubjectDescription(VD);
842
843 if (const auto *CE = dyn_cast<CallExpr>(Val: E)) {
844 const auto *FD = CE->getDirectCallee();
845 if (!FD)
846 return "result of call";
847 std::string Name;
848 llvm::raw_string_ostream OS(Name);
849 FD->getNameForDiagnostic(OS, Policy: S.getPrintingPolicy(),
850 /*Qualified=*/Qualified: false);
851 if (isAllocatingFunction(FD: *FD))
852 return "object allocated by '" + Name + "'";
853 return "result of call to '" + Name + "'";
854 }
855
856 // TODO: Handle other expression types.
857 return "expression";
858 }
859
860 bool shouldShowInAliasChain(const Expr *CurrExpr, const Expr *LastExpr) {
861 CurrExpr = ignoreParensAndImpCasts(E: CurrExpr);
862 LastExpr = ignoreParensAndImpCasts(E: LastExpr);
863
864 if (!isa<CallExpr, DeclRefExpr>(Val: CurrExpr))
865 return false;
866 // Source ranges can be used to filter out many implicit expressions,
867 // because operations between class objects often involve numerous implicit
868 // conversions, yet they share the same source range.
869 return CurrExpr->getSourceRange() != LastExpr->getSourceRange();
870 }
871
872 void reportAliasingChain(llvm::ArrayRef<const Expr *> OriginExprChain) {
873 if (OriginExprChain.empty())
874 return;
875
876 const Expr *LastExpr = OriginExprChain.back();
877 const Expr *VisibleLastExpr = LastExpr;
878 std::string IssueStr = getDiagSubjectDescription(E: VisibleLastExpr);
879
880 for (const Expr *CurrExpr : reverse(C: OriginExprChain.drop_back())) {
881 if (!shouldShowInAliasChain(CurrExpr, LastExpr: VisibleLastExpr)) {
882 LastExpr = CurrExpr;
883 continue;
884 }
885 std::optional<LifetimeBoundParamInfo> ParamInfo =
886 getTrackingInfoForCallArg(Call: CurrExpr, Source: LastExpr);
887 LastExpr = CurrExpr;
888 if (ParamInfo) {
889 bool IsImplicitObject = isa<const CXXMethodDecl *>(Val: *ParamInfo);
890 bool IsInferred = true;
891 std::string ParamName;
892 if (!IsImplicitObject) {
893 const auto *Param = cast<const ParmVarDecl *>(Val&: *ParamInfo);
894 if (const auto *Attr = Param->getAttr<LifetimeBoundAttr>())
895 IsInferred = Attr->isImplicit();
896 ParamName = Param->getIdentifier()
897 ? "'" + Param->getNameAsString() + "'"
898 : "'<unnamed>'";
899 } else if (const auto *Attr = getImplicitObjectParamLifetimeBoundAttr(
900 FD: cast<const CXXMethodDecl *>(Val&: *ParamInfo))) {
901 IsInferred = Attr->isImplicit();
902 }
903 S.Diag(Loc: CurrExpr->getBeginLoc(),
904 DiagID: diag::note_lifetime_safety_aliases_storage_lifetimebound)
905 << CurrExpr->getSourceRange() << getDiagSubjectDescription(E: CurrExpr)
906 << IssueStr << IsImplicitObject << ParamName << IsInferred;
907 } else
908 S.Diag(Loc: CurrExpr->getBeginLoc(),
909 DiagID: diag::note_lifetime_safety_aliases_storage)
910 << CurrExpr->getSourceRange() << getDiagSubjectDescription(E: CurrExpr)
911 << IssueStr;
912 VisibleLastExpr = CurrExpr;
913 }
914 }
915
916 LifetimeBoundMacroCache ClangLifetimeBoundMacroCache;
917 LifetimeBoundMacroCache GNULifetimeBoundMacroCache;
918 Sema &S;
919};
920
921} // namespace clang::lifetimes
922
923#endif // LLVM_CLANG_LIB_SEMA_SEMALIFETIMESAFETY_H
924