Debian Codegraph @

clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp

raw
1 //===- FactsGenerator.cpp - Lifetime Facts Generation -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include <cassert>
10 #include <string>
11
12 #include "clang/AST/OperationKinds.h"
13 #include "clang/Analysis/Analyses/LifetimeSafety/FactsGenerator.h"
14 #include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
15 #include "clang/Analysis/Analyses/LifetimeSafety/Origins.h"
16 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
17 #include "llvm/Support/Casting.h"
18 #include "llvm/Support/Signals.h"
19 #include "llvm/Support/TimeProfiler.h"
20
21 namespace clang::lifetimes::internal {
22 using llvm::isa_and_present;
23
24 OriginList *FactsGenerator::getOriginsList(const ValueDecl &D) {
25 return FactMgr.getOriginMgr().getOrCreateList(&D);
26 }
27 OriginList *FactsGenerator::getOriginsList(const Expr &E) {
28 return FactMgr.getOriginMgr().getOrCreateList(&E);
29 }
30
31 /// Propagates origin information from Src to Dst through all levels of
32 /// indirection, creating OriginFlowFacts at each level.
33 ///
34 /// This function enforces a critical type-safety invariant: both lists must
35 /// have the same shape (same depth/structure). This invariant ensures that
36 /// origins flow only between compatible types during expression evaluation.
37 ///
38 /// Examples:
39 /// - `int* p = &x;` flows origins from `&x` (depth 1) to `p` (depth 1)
40 /// - `int** pp = &p;` flows origins from `&p` (depth 2) to `pp` (depth 2)
41 /// * Level 1: pp <- p's address
42 /// * Level 2: (*pp) <- what p points to (i.e., &x)
43 /// - `View v = obj;` flows origins from `obj` (depth 1) to `v` (depth 1)
44 void FactsGenerator::flow(OriginList *Dst, OriginList *Src, bool Kill) {
45 if (!Dst)
46 return;
47 assert(Src &&
48 "Dst is non-null but Src is null. List must have the same length");
49 assert(Dst->getLength() == Src->getLength() &&
50 "Lists must have the same length");
51
52 while (Dst && Src) {
53 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
54 Dst->getOuterOriginID(), Src->getOuterOriginID(), Kill));
55 Dst = Dst->peelOuterOrigin();
56 Src = Src->peelOuterOrigin();
57 }
58 }
59
60 /// Creates a loan for the storage path of a given declaration reference.
61 /// This function should be called whenever a DeclRefExpr represents a borrow.
62 /// \param DRE The declaration reference expression that initiates the borrow.
63 /// \return The new Loan on success, nullptr otherwise.
64 static const PathLoan *createLoan(FactManager &FactMgr,
65 const DeclRefExpr *DRE) {
66 if (const auto *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
67 AccessPath Path(VD);
68 // The loan is created at the location of the DeclRefExpr.
69 return FactMgr.getLoanMgr().createLoan<PathLoan>(Path, DRE);
70 }
71 return nullptr;
72 }
73
74 void FactsGenerator::run() {
75 llvm::TimeTraceScope TimeProfile("FactGenerator");
76 const CFG &Cfg = *AC.getCFG();
77 llvm::SmallVector<Fact *> PlaceholderLoanFacts = issuePlaceholderLoans();
78 // Iterate through the CFG blocks in reverse post-order to ensure that
79 // initializations and destructions are processed in the correct sequence.
80 for (const CFGBlock *Block : *AC.getAnalysis<PostOrderCFGView>()) {
81 CurrentBlockFacts.clear();
82 EscapesInCurrentBlock.clear();
83 if (Block == &Cfg.getEntry())
84 CurrentBlockFacts.append(PlaceholderLoanFacts.begin(),
85 PlaceholderLoanFacts.end());
86 for (unsigned I = 0; I < Block->size(); ++I) {
87 const CFGElement &Element = Block->Elements[I];
88 if (std::optional<CFGStmt> CS = Element.getAs<CFGStmt>())
89 Visit(CS->getStmt());
90 else if (std::optional<CFGLifetimeEnds> LifetimeEnds =
91 Element.getAs<CFGLifetimeEnds>())
92 handleLifetimeEnds(*LifetimeEnds);
93 }
94 CurrentBlockFacts.append(EscapesInCurrentBlock.begin(),
95 EscapesInCurrentBlock.end());
96 FactMgr.addBlockFacts(Block, CurrentBlockFacts);
97 }
98 }
99
100 /// Simulates LValueToRValue conversion by peeling the outer lvalue origin
101 /// if the expression is a GLValue. For pointer/view GLValues, this strips
102 /// the origin representing the storage location to get the origins of the
103 /// pointed-to value.
104 ///
105 /// Example: For `View& v`, returns the origin of what v points to, not v's
106 /// storage.
107 static OriginList *getRValueOrigins(const Expr *E, OriginList *List) {
108 if (!List)
109 return nullptr;
110 return E->isGLValue() ? List->peelOuterOrigin() : List;
111 }
112
113 void FactsGenerator::VisitDeclStmt(const DeclStmt *DS) {
114 for (const Decl *D : DS->decls())
115 if (const auto *VD = dyn_cast<VarDecl>(D))
116 if (const Expr *InitExpr = VD->getInit()) {
117 OriginList *VDList = getOriginsList(*VD);
118 if (!VDList)
119 continue;
120 OriginList *InitList = getOriginsList(*InitExpr);
121 assert(InitList && "VarDecl had origins but InitExpr did not");
122 flow(VDList, InitList, /*Kill=*/true);
123 }
124 }
125
126 void FactsGenerator::VisitDeclRefExpr(const DeclRefExpr *DRE) {
127 // Skip function references as their lifetimes are not interesting. Skip non
128 // GLValues (like EnumConstants).
129 if (DRE->getFoundDecl()->isFunctionOrFunctionTemplate() || !DRE->isGLValue())
130 return;
131 handleUse(DRE);
132 // For all declarations with storage (non-references), we issue a loan
133 // representing the borrow of the variable's storage itself.
134 //
135 // Examples:
136 // - `int x; x` issues loan to x's storage
137 // - `int* p; p` issues loan to p's storage (the pointer variable)
138 // - `View v; v` issues loan to v's storage (the view object)
139 // - `int& r = x; r` issues no loan (r has no storage, it's an alias to x)
140 if (doesDeclHaveStorage(DRE->getDecl())) {
141 const Loan *L = createLoan(FactMgr, DRE);
142 assert(L);
143 OriginList *List = getOriginsList(*DRE);
144 assert(List &&
145 "gl-value DRE of non-pointer type should have an origin list");
146 // This loan specifically tracks borrowing the variable's storage location
147 // itself and is issued to outermost origin (List->OID).
148 CurrentBlockFacts.push_back(
149 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
150 }
151 }
152
153 void FactsGenerator::VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
154 if (isGslPointerType(CCE->getType())) {
155 handleGSLPointerConstruction(CCE);
156 return;
157 }
158 }
159
160 void FactsGenerator::VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
161 // Specifically for conversion operators,
162 // like `std::string_view p = std::string{};`
163 if (isGslPointerType(MCE->getType()) &&
164 isa_and_present<CXXConversionDecl>(MCE->getCalleeDecl()) &&
165 isGslOwnerType(MCE->getImplicitObjectArgument()->getType())) {
166 // The argument is the implicit object itself.
167 handleFunctionCall(MCE, MCE->getMethodDecl(),
168 {MCE->getImplicitObjectArgument()},
169 /*IsGslConstruction=*/true);
170 return;
171 }
172 if (const CXXMethodDecl *Method = MCE->getMethodDecl()) {
173 // Construct the argument list, with the implicit 'this' object as the
174 // first argument.
175 llvm::SmallVector<const Expr *, 4> Args;
176 Args.push_back(MCE->getImplicitObjectArgument());
177 Args.append(MCE->getArgs(), MCE->getArgs() + MCE->getNumArgs());
178
179 handleFunctionCall(MCE, Method, Args, /*IsGslConstruction=*/false);
180 }
181 }
182
183 void FactsGenerator::VisitCallExpr(const CallExpr *CE) {
184 handleFunctionCall(CE, CE->getDirectCallee(),
185 {CE->getArgs(), CE->getNumArgs()});
186 }
187
188 void FactsGenerator::VisitCXXNullPtrLiteralExpr(
189 const CXXNullPtrLiteralExpr *N) {
190 /// TODO: Handle nullptr expr as a special 'null' loan. Uninitialized
191 /// pointers can use the same type of loan.
192 getOriginsList(*N);
193 }
194
195 void FactsGenerator::VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
196 OriginList *Dest = getOriginsList(*ICE);
197 if (!Dest)
198 return;
199 OriginList *SrcList = getOriginsList(*ICE->getSubExpr());
200
201 switch (ICE->getCastKind()) {
202 case CK_LValueToRValue:
203 // TODO: Decide what to do for x-values here.
204 if (!ICE->getSubExpr()->isLValue())
205 return;
206
207 assert(SrcList && "LValue being cast to RValue has no origin list");
208 // The result of an LValue-to-RValue cast on a pointer lvalue (like `q` in
209 // `int *p, *q; p = q;`) should propagate the inner origin (what the pointer
210 // points to), not the outer origin (the pointer's storage location). Strip
211 // the outer lvalue origin.
212 flow(getOriginsList(*ICE), getRValueOrigins(ICE->getSubExpr(), SrcList),
213 /*Kill=*/true);
214 return;
215 case CK_NullToPointer:
216 getOriginsList(*ICE);
217 // TODO: Flow into them a null origin.
218 return;
219 case CK_NoOp:
220 case CK_ConstructorConversion:
221 case CK_UserDefinedConversion:
222 case CK_UncheckedDerivedToBase:
223 case CK_DerivedToBase:
224 flow(Dest, SrcList, /*Kill=*/true);
225 return;
226 case CK_FunctionToPointerDecay:
227 case CK_BuiltinFnToFnPtr:
228 case CK_ArrayToPointerDecay:
229 // Ignore function-to-pointer decays.
230 return;
231 default:
232 return;
233 }
234 }
235
236 void FactsGenerator::VisitUnaryOperator(const UnaryOperator *UO) {
237 switch (UO->getOpcode()) {
238 case UO_AddrOf: {
239 const Expr *SubExpr = UO->getSubExpr();
240 // The origin of an address-of expression (e.g., &x) is the origin of
241 // its sub-expression (x). This fact will cause the dataflow analysis
242 // to propagate any loans held by the sub-expression's origin to the
243 // origin of this UnaryOperator expression.
244 killAndFlowOrigin(*UO, *SubExpr);
245 return;
246 }
247 case UO_Deref: {
248 const Expr *SubExpr = UO->getSubExpr();
249 killAndFlowOrigin(*UO, *SubExpr);
250 return;
251 }
252 default:
253 return;
254 }
255 }
256
257 void FactsGenerator::VisitReturnStmt(const ReturnStmt *RS) {
258 if (const Expr *RetExpr = RS->getRetValue()) {
259 if (OriginList *List = getOriginsList(*RetExpr))
260 for (OriginList *L = List; L != nullptr; L = L->peelOuterOrigin())
261 EscapesInCurrentBlock.push_back(FactMgr.createFact<OriginEscapesFact>(
262 L->getOuterOriginID(), RetExpr));
263 }
264 }
265
266 void FactsGenerator::handleAssignment(const Expr *LHSExpr,
267 const Expr *RHSExpr) {
268 if (const auto *DRE_LHS =
269 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenImpCasts())) {
270 OriginList *LHSList = getOriginsList(*DRE_LHS);
271 assert(LHSList && "LHS is a DRE and should have an origin list");
272 OriginList *RHSList = getOriginsList(*RHSExpr);
273
274 // For operator= with reference parameters (e.g.,
275 // `View& operator=(const View&)`), the RHS argument stays an lvalue,
276 // unlike built-in assignment where LValueToRValue cast strips the outer
277 // lvalue origin. Strip it manually to get the actual value origins being
278 // assigned.
279 RHSList = getRValueOrigins(RHSExpr, RHSList);
280
281 markUseAsWrite(DRE_LHS);
282 // Kill the old loans of the destination origin and flow the new loans
283 // from the source origin.
284 flow(LHSList->peelOuterOrigin(), RHSList, /*Kill=*/true);
285 }
286 }
287
288 void FactsGenerator::VisitBinaryOperator(const BinaryOperator *BO) {
289 // TODO: Handle pointer arithmetic (e.g., `p + 1` or `1 + p`) where the
290 // result should have the same loans as the pointer operand.
291 if (BO->isCompoundAssignmentOp())
292 return;
293 if (BO->isAssignmentOp())
294 handleAssignment(BO->getLHS(), BO->getRHS());
295 // TODO: Handle assignments involving dereference like `*p = q`.
296 }
297
298 void FactsGenerator::VisitConditionalOperator(const ConditionalOperator *CO) {
299 if (hasOrigins(CO)) {
300 // Merge origins from both branches of the conditional operator.
301 // We kill to clear the initial state and merge both origins into it.
302 killAndFlowOrigin(*CO, *CO->getTrueExpr());
303 flowOrigin(*CO, *CO->getFalseExpr());
304 }
305 }
306
307 void FactsGenerator::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE) {
308 // Assignment operators have special "kill-then-propagate" semantics
309 // and are handled separately.
310 if (OCE->getOperator() == OO_Equal && OCE->getNumArgs() == 2 &&
311 hasOrigins(OCE->getArg(0)->getType())) {
312 handleAssignment(OCE->getArg(0), OCE->getArg(1));
313 return;
314 }
315 VisitCallExpr(OCE);
316 }
317
318 void FactsGenerator::VisitCXXFunctionalCastExpr(
319 const CXXFunctionalCastExpr *FCE) {
320 // Check if this is a test point marker. If so, we are done with this
321 // expression.
322 if (handleTestPoint(FCE))
323 return;
324 if (isGslPointerType(FCE->getType()))
325 killAndFlowOrigin(*FCE, *FCE->getSubExpr());
326 }
327
328 void FactsGenerator::VisitInitListExpr(const InitListExpr *ILE) {
329 if (!hasOrigins(ILE))
330 return;
331 // For list initialization with a single element, like `View{...}`, the
332 // origin of the list itself is the origin of its single element.
333 if (ILE->getNumInits() == 1)
334 killAndFlowOrigin(*ILE, *ILE->getInit(0));
335 }
336
337 void FactsGenerator::VisitMaterializeTemporaryExpr(
338 const MaterializeTemporaryExpr *MTE) {
339 OriginList *MTEList = getOriginsList(*MTE);
340 if (!MTEList)
341 return;
342 OriginList *SubExprList = getOriginsList(*MTE->getSubExpr());
343 if (MTE->isGLValue()) {
344 assert(!SubExprList ||
345 MTEList->getLength() == SubExprList->getLength() + 1 &&
346 "MTE top level origin should contain a loan to the MTE itself");
347 MTEList = getRValueOrigins(MTE, MTEList);
348 // TODO: Issue a loan to the MTE.
349 flow(MTEList, SubExprList, /*Kill=*/true);
350 } else {
351 assert(MTE->isXValue());
352 flow(MTEList, SubExprList, /*Kill=*/true);
353 }
354 }
355
356 void FactsGenerator::handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds) {
357 /// TODO: Handle loans to temporaries.
358 const VarDecl *LifetimeEndsVD = LifetimeEnds.getVarDecl();
359 if (!LifetimeEndsVD)
360 return;
361 // Iterate through all loans to see if any expire.
362 for (const auto *Loan : FactMgr.getLoanMgr().getLoans()) {
363 if (const auto *BL = dyn_cast<PathLoan>(Loan)) {
364 // Check if the loan is for a stack variable and if that variable
365 // is the one being destructed.
366 if (BL->getAccessPath().D == LifetimeEndsVD)
367 CurrentBlockFacts.push_back(FactMgr.createFact<ExpireFact>(
368 BL->getID(), LifetimeEnds.getTriggerStmt()->getEndLoc()));
369 }
370 }
371 }
372
373 void FactsGenerator::handleGSLPointerConstruction(const CXXConstructExpr *CCE) {
374 assert(isGslPointerType(CCE->getType()));
375 if (CCE->getNumArgs() != 1)
376 return;
377
378 const Expr *Arg = CCE->getArg(0);
379 if (isGslPointerType(Arg->getType())) {
380 OriginList *ArgList = getOriginsList(*Arg);
381 assert(ArgList && "GSL pointer argument should have an origin list");
382 // GSL pointer is constructed from another gsl pointer.
383 // Example:
384 // View(View v);
385 // View(const View &v);
386 ArgList = getRValueOrigins(Arg, ArgList);
387 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
388 } else {
389 // This could be a new borrow.
390 // TODO: Add code example here.
391 handleFunctionCall(CCE, CCE->getConstructor(),
392 {CCE->getArgs(), CCE->getNumArgs()},
393 /*IsGslConstruction=*/true);
394 }
395 }
396
397 /// Checks if a call-like expression creates a borrow by passing a value to a
398 /// reference parameter, creating an IssueFact if it does.
399 /// \param IsGslConstruction True if this is a GSL construction where all
400 /// argument origins should flow to the returned origin.
401 void FactsGenerator::handleFunctionCall(const Expr *Call,
402 const FunctionDecl *FD,
403 ArrayRef<const Expr *> Args,
404 bool IsGslConstruction) {
405 OriginList *CallList = getOriginsList(*Call);
406 // Ignore functions returning values with no origin.
407 if (!FD || !CallList)
408 return;
409 auto IsArgLifetimeBound = [FD](unsigned I) -> bool {
410 const ParmVarDecl *PVD = nullptr;
411 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD);
412 Method && Method->isInstance()) {
413 if (I == 0)
414 // For the 'this' argument, the attribute is on the method itself.
415 return implicitObjectParamIsLifetimeBound(Method) ||
416 shouldTrackImplicitObjectArg(Method);
417 if ((I - 1) < Method->getNumParams())
418 // For explicit arguments, find the corresponding parameter
419 // declaration.
420 PVD = Method->getParamDecl(I - 1);
421 } else if (I == 0 && shouldTrackFirstArgument(FD)) {
422 return true;
423 } else if (I < FD->getNumParams()) {
424 // For free functions or static methods.
425 PVD = FD->getParamDecl(I);
426 }
427 return PVD ? PVD->hasAttr<clang::LifetimeBoundAttr>() : false;
428 };
429 if (Args.empty())
430 return;
431 bool KillSrc = true;
432 for (unsigned I = 0; I < Args.size(); ++I) {
433 OriginList *ArgList = getOriginsList(*Args[I]);
434 if (!ArgList)
435 continue;
436 if (IsGslConstruction) {
437 // TODO: document with code example.
438 // std::string_view(const std::string_view& from)
439 if (isGslPointerType(Args[I]->getType())) {
440 assert(!Args[I]->isGLValue() || ArgList->getLength() >= 2);
441 ArgList = getRValueOrigins(Args[I], ArgList);
442 }
443 if (isGslOwnerType(Args[I]->getType())) {
444 // GSL construction creates a view that borrows from arguments.
445 // This implies flowing origins through the list structure.
446 flow(CallList, ArgList, KillSrc);
447 KillSrc = false;
448 }
449 } else if (IsArgLifetimeBound(I)) {
450 // Lifetimebound on a non-GSL-ctor function means the returned
451 // pointer/reference itself must not outlive the arguments. This
452 // only constraints the top-level origin.
453 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
454 CallList->getOuterOriginID(), ArgList->getOuterOriginID(), KillSrc));
455 KillSrc = false;
456 }
457 }
458 }
459
460 /// Checks if the expression is a `void("__lifetime_test_point_...")` cast.
461 /// If so, creates a `TestPointFact` and returns true.
462 bool FactsGenerator::handleTestPoint(const CXXFunctionalCastExpr *FCE) {
463 if (!FCE->getType()->isVoidType())
464 return false;
465
466 const auto *SubExpr = FCE->getSubExpr()->IgnoreParenImpCasts();
467 if (const auto *SL = dyn_cast<StringLiteral>(SubExpr)) {
468 llvm::StringRef LiteralValue = SL->getString();
469 const std::string Prefix = "__lifetime_test_point_";
470
471 if (LiteralValue.starts_with(Prefix)) {
472 StringRef Annotation = LiteralValue.drop_front(Prefix.length());
473 CurrentBlockFacts.push_back(
474 FactMgr.createFact<TestPointFact>(Annotation));
475 return true;
476 }
477 }
478 return false;
479 }
480
481 // A DeclRefExpr will be treated as a use of the referenced decl. It will be
482 // checked for use-after-free unless it is later marked as being written to
483 // (e.g. on the left-hand side of an assignment).
484 void FactsGenerator::handleUse(const DeclRefExpr *DRE) {
485 OriginList *List = getOriginsList(*DRE);
486 if (!List)
487 return;
488 // Remove the outer layer of origin which borrows from the decl directly. This
489 // is a use of the underlying decl.
490 List = getRValueOrigins(DRE, List);
491 // Skip if there is no inner origin (e.g., when it is not a pointer type).
492 if (!List)
493 return;
494 UseFact *UF = FactMgr.createFact<UseFact>(DRE, List);
495 CurrentBlockFacts.push_back(UF);
496 assert(!UseFacts.contains(DRE));
497 UseFacts[DRE] = UF;
498 }
499
500 void FactsGenerator::markUseAsWrite(const DeclRefExpr *DRE) {
501 if (UseFacts.contains(DRE))
502 UseFacts[DRE]->markAsWritten();
503 }
504
505 // Creates an IssueFact for a new placeholder loan for each pointer or reference
506 // parameter at the function's entry.
507 llvm::SmallVector<Fact *> FactsGenerator::issuePlaceholderLoans() {
508 const auto *FD = dyn_cast<FunctionDecl>(AC.getDecl());
509 if (!FD)
510 return {};
511
512 llvm::SmallVector<Fact *> PlaceholderLoanFacts;
513 for (const ParmVarDecl *PVD : FD->parameters()) {
514 OriginList *List = getOriginsList(*PVD);
515 if (!List)
516 continue;
517 const PlaceholderLoan *L =
518 FactMgr.getLoanMgr().createLoan<PlaceholderLoan>(PVD);
519 PlaceholderLoanFacts.push_back(
520 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
521 }
522 return PlaceholderLoanFacts;
523 }
524
525 } // namespace clang::lifetimes::internal