clang 23.0.0git
FactsGenerator.cpp
Go to the documentation of this file.
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/Decl.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/Expr.h"
15#include "clang/AST/ExprCXX.h"
22#include "clang/Analysis/CFG.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/Casting.h"
27#include "llvm/Support/Signals.h"
28#include "llvm/Support/TimeProfiler.h"
29
31using llvm::isa_and_present;
32
33OriginList *FactsGenerator::getOriginsList(const ValueDecl &D) {
34 return FactMgr.getOriginMgr().getOrCreateList(&D);
35}
36OriginList *FactsGenerator::getOriginsList(const Expr &E) {
37 return FactMgr.getOriginMgr().getOrCreateList(&E);
38}
39
40bool FactsGenerator::hasOrigins(QualType QT) const {
41 return FactMgr.getOriginMgr().hasOrigins(QT);
42}
43
44bool FactsGenerator::hasOrigins(const Expr *E) const {
45 return FactMgr.getOriginMgr().hasOrigins(E);
46}
47
48/// Propagates origin information from Src to Dst through all levels of
49/// indirection, creating OriginFlowFacts at each level.
50///
51/// This function enforces a critical type-safety invariant: both lists must
52/// have the same shape (same depth/structure). This invariant ensures that
53/// origins flow only between compatible types during expression evaluation.
54///
55/// Examples:
56/// - `int* p = &x;` flows origins from `&x` (depth 1) to `p` (depth 1)
57/// - `int** pp = &p;` flows origins from `&p` (depth 2) to `pp` (depth 2)
58/// * Level 1: pp <- p's address
59/// * Level 2: (*pp) <- what p points to (i.e., &x)
60/// - `View v = obj;` flows origins from `obj` (depth 1) to `v` (depth 1)
61void FactsGenerator::flow(OriginList *Dst, OriginList *Src, bool Kill) {
62 if (!Dst)
63 return;
64 assert(Src &&
65 "Dst is non-null but Src is null. List must have the same length");
66 assert(Dst->getLength() == Src->getLength() &&
67 "Lists must have the same length");
68
69 while (Dst && Src) {
70 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
71 Dst->getOuterOriginID(), Src->getOuterOriginID(), Kill));
72 Dst = Dst->peelOuterOrigin();
73 Src = Src->peelOuterOrigin();
74 }
75}
76
77/// Creates a loan for the storage path of a given declaration reference.
78/// This function should be called whenever a DeclRefExpr represents a borrow.
79/// \param DRE The declaration reference expression that initiates the borrow.
80/// \return The new Loan on success, nullptr otherwise.
81static const Loan *createLoan(FactManager &FactMgr, const DeclRefExpr *DRE) {
82 const ValueDecl *VD = DRE->getDecl();
83 AccessPath Path(VD);
84 // The loan is created at the location of the DeclRefExpr.
85 return FactMgr.getLoanMgr().createLoan(Path, DRE);
86}
87
88/// Creates a loan for the storage location of a temporary object.
89/// \param MTE The MaterializeTemporaryExpr that represents the temporary
90/// binding. \return The new Loan.
91static const Loan *createLoan(FactManager &FactMgr,
92 const MaterializeTemporaryExpr *MTE) {
93 AccessPath Path(MTE);
94 return FactMgr.getLoanMgr().createLoan(Path, MTE);
95}
96
97/// Creates a loan for an allocation through 'new'
98/// \param NE The CXXNewExpr that represents the allocation
99/// \return The new Loan on success, nullptr otherwise
100static const Loan *createLoan(FactManager &FactMgr, const CXXNewExpr *NE) {
101 AccessPath Path(NE);
102 return FactMgr.getLoanMgr().createLoan(Path, NE);
103}
104
106 llvm::TimeTraceScope TimeProfile("FactGenerator");
107 const CFG &Cfg = *AC.getCFG();
108 llvm::SmallVector<Fact *> PlaceholderLoanFacts = issuePlaceholderLoans();
109 // Iterate through the CFG blocks in reverse post-order to ensure that
110 // initializations and destructions are processed in the correct sequence.
111 for (const CFGBlock *Block : *AC.getAnalysis<PostOrderCFGView>()) {
112 CurrentBlockFacts.clear();
113 EscapesInCurrentBlock.clear();
114 CurrentBlock = Block;
115 if (Block == &Cfg.getEntry())
116 CurrentBlockFacts.append(PlaceholderLoanFacts.begin(),
117 PlaceholderLoanFacts.end());
118 for (unsigned I = 0; I < Block->size(); ++I) {
119 const CFGElement &Element = Block->Elements[I];
120 if (std::optional<CFGStmt> CS = Element.getAs<CFGStmt>())
121 Visit(CS->getStmt());
122 else if (std::optional<CFGInitializer> Initializer =
123 Element.getAs<CFGInitializer>())
124 handleCXXCtorInitializer(Initializer->getInitializer());
125 else if (std::optional<CFGLifetimeEnds> LifetimeEnds =
126 Element.getAs<CFGLifetimeEnds>())
127 handleLifetimeEnds(*LifetimeEnds);
128 else if (std::optional<CFGFullExprCleanup> FullExprCleanup =
129 Element.getAs<CFGFullExprCleanup>()) {
130 handleFullExprCleanup(*FullExprCleanup);
131 }
132 }
133 if (Block == &Cfg.getExit())
134 handleExitBlock();
135
136 CurrentBlockFacts.append(EscapesInCurrentBlock.begin(),
137 EscapesInCurrentBlock.end());
138 FactMgr.addBlockFacts(Block, CurrentBlockFacts);
139 }
140}
141
142/// Simulates LValueToRValue conversion by peeling the outer lvalue origin
143/// if the expression is a GLValue. For pointer/view GLValues, this strips
144/// the origin representing the storage location to get the origins of the
145/// pointed-to value.
146///
147/// Example: For `View& v`, returns the origin of what v points to, not v's
148/// storage.
149static OriginList *getRValueOrigins(const Expr *E, OriginList *List) {
150 if (!List)
151 return nullptr;
152 return E->isGLValue() ? List->peelOuterOrigin() : List;
153}
154
156 for (const Decl *D : DS->decls())
157 if (const auto *VD = dyn_cast<VarDecl>(D))
158 if (const Expr *InitExpr = VD->getInit()) {
159 OriginList *VDList = getOriginsList(*VD);
160 if (!VDList)
161 continue;
162 OriginList *InitList = getOriginsList(*InitExpr);
163 assert(InitList && "VarDecl had origins but InitExpr did not");
164 flow(VDList, InitList, /*Kill=*/true);
165 }
166}
167
169 // Skip function references as their lifetimes are not interesting. Skip non
170 // GLValues (like EnumConstants).
171 if (DRE->getFoundDecl()->isFunctionOrFunctionTemplate() || !DRE->isGLValue())
172 return;
173 handleUse(DRE);
174 // For all declarations with storage (non-references), we issue a loan
175 // representing the borrow of the variable's storage itself.
176 //
177 // Examples:
178 // - `int x; x` issues loan to x's storage
179 // - `int* p; p` issues loan to p's storage (the pointer variable)
180 // - `View v; v` issues loan to v's storage (the view object)
181 // - `int& r = x; r` issues no loan (r has no storage, it's an alias to x)
182 if (doesDeclHaveStorage(DRE->getDecl())) {
183 const Loan *L = createLoan(FactMgr, DRE);
184 assert(L);
185 OriginList *List = getOriginsList(*DRE);
186 assert(List &&
187 "gl-value DRE of non-pointer type should have an origin list");
188 // This loan specifically tracks borrowing the variable's storage location
189 // itself and is issued to outermost origin (List->OID).
190 CurrentBlockFacts.push_back(
191 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
192 }
193}
194
196 if (isGslPointerType(CCE->getType())) {
197 handleGSLPointerConstruction(CCE);
198 return;
199 }
200 // For defaulted (implicit or `= default`) copy/move constructors, propagate
201 // origins directly. User-defined copy/move constructors are not handled here
202 // as they have opaque semantics.
204 CCE->getConstructor()->isDefaulted() && CCE->getNumArgs() == 1 &&
205 hasOrigins(CCE->getType())) {
206 const Expr *Arg = CCE->getArg(0);
207 if (OriginList *ArgList = getRValueOrigins(Arg, getOriginsList(*Arg))) {
208 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
209 return;
210 }
211 }
212 // Standard library callable wrappers (e.g., std::function) propagate the
213 // stored lambda's origins.
214 if (const auto *RD = CCE->getType()->getAsCXXRecordDecl();
215 RD && isStdCallableWrapperType(RD) && CCE->getNumArgs() == 1) {
216 const Expr *Arg = CCE->getArg(0);
217 if (OriginList *ArgList = getRValueOrigins(Arg, getOriginsList(*Arg))) {
218 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
219 return;
220 }
221 }
222 handleFunctionCall(CCE, CCE->getConstructor(),
223 {CCE->getArgs(), CCE->getNumArgs()},
224 /*IsGslConstruction=*/false);
225}
226
228 if (const Expr *Init = DIE->getExpr())
229 killAndFlowOrigin(*DIE, *Init);
230}
231
232void FactsGenerator::handleCXXCtorInitializer(const CXXCtorInitializer *CII) {
233 // Flows origins from the initializer expression to the field.
234 // Example: `MyObj(std::string s) : view(s) {}`
235 if (const FieldDecl *FD = CII->getAnyMember())
236 killAndFlowOrigin(*FD, *CII->getInit());
237}
238
240 // Specifically for conversion operators,
241 // like `std::string_view p = std::string{};`
242 if (isGslPointerType(MCE->getType()) &&
243 isa_and_present<CXXConversionDecl>(MCE->getCalleeDecl()) &&
245 // The argument is the implicit object itself.
246 handleFunctionCall(MCE, MCE->getMethodDecl(),
247 {MCE->getImplicitObjectArgument()},
248 /*IsGslConstruction=*/true);
249 return;
250 }
251 if (const CXXMethodDecl *Method = MCE->getMethodDecl()) {
252 // Construct the argument list, with the implicit 'this' object as the
253 // first argument.
255 Args.push_back(MCE->getImplicitObjectArgument());
256 Args.append(MCE->getArgs(), MCE->getArgs() + MCE->getNumArgs());
257
258 handleFunctionCall(MCE, Method, Args, /*IsGslConstruction=*/false);
259 }
260}
261
263 auto *MD = ME->getMemberDecl();
264 if (isa<FieldDecl>(MD) && doesDeclHaveStorage(MD)) {
265 assert(ME->isGLValue() && "Field member should be GL value");
266 OriginList *Dst = getOriginsList(*ME);
267 assert(Dst && "Field member should have an origin list as it is GL value");
268 OriginList *Src = getOriginsList(*ME->getBase());
269 assert(Src && "Base expression should be a pointer/reference type");
270 // The field's glvalue (outermost origin) holds the same loans as the base
271 // expression.
272 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
273 Dst->getOuterOriginID(), Src->getOuterOriginID(),
274 /*Kill=*/true));
275 }
276}
277
279 handleFunctionCall(CE, CE->getDirectCallee(),
280 {CE->getArgs(), CE->getNumArgs()});
281}
282
284 const CXXNullPtrLiteralExpr *N) {
285 /// TODO: Handle nullptr expr as a special 'null' loan. Uninitialized
286 /// pointers can use the same type of loan.
287 getOriginsList(*N);
288}
289
291 OriginList *Dest = getOriginsList(*CE);
292 if (!Dest)
293 return;
294 const Expr *SubExpr = CE->getSubExpr();
295 OriginList *Src = getOriginsList(*SubExpr);
296
297 switch (CE->getCastKind()) {
298 case CK_LValueToRValue:
299 if (!SubExpr->isGLValue())
300 return;
301
302 assert(Src && "LValue being cast to RValue has no origin list");
303 // The result of an LValue-to-RValue cast on a pointer lvalue (like `q` in
304 // `int *p, *q; p = q;`) should propagate the inner origin (what the pointer
305 // points to), not the outer origin (the pointer's storage location). Strip
306 // the outer lvalue origin.
307 flow(getOriginsList(*CE), getRValueOrigins(SubExpr, Src),
308 /*Kill=*/true);
309 return;
310 case CK_NullToPointer:
311 getOriginsList(*CE);
312 // TODO: Flow into them a null origin.
313 return;
314 case CK_NoOp:
315 case CK_ConstructorConversion:
316 case CK_UserDefinedConversion:
317 flow(Dest, Src, /*Kill=*/true);
318 return;
319 case CK_UncheckedDerivedToBase:
320 case CK_DerivedToBase:
321 // It is possible that the derived class and base class have different
322 // gsl::Pointer annotations. Skip if their origin shape differ.
323 if (Dest && Src && Dest->getLength() == Src->getLength())
324 flow(Dest, Src, /*Kill=*/true);
325 return;
326 case CK_ArrayToPointerDecay:
327 assert(Src && "Array expression should have origins as it is GL value");
328 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
329 Dest->getOuterOriginID(), Src->getOuterOriginID(), /*Kill=*/true));
330 return;
331 case CK_FunctionToPointerDecay:
332 case CK_BuiltinFnToFnPtr:
333 // Ignore function-to-pointer decays.
334 return;
335 case CK_BitCast:
336 // OriginLists for Src and Dst may differ here. For example when casting
337 // from int** to void*
338 if (Src && Dest && Dest->getLength() == Src->getLength())
339 flow(Dest, Src, /*Kill=*/true);
340 return;
341 default:
342 return;
343 }
344}
345
347 switch (UO->getOpcode()) {
348 case UO_AddrOf: {
349 const Expr *SubExpr = UO->getSubExpr();
350 // The origin of an address-of expression (e.g., &x) is the origin of
351 // its sub-expression (x). This fact will cause the dataflow analysis
352 // to propagate any loans held by the sub-expression's origin to the
353 // origin of this UnaryOperator expression.
354 killAndFlowOrigin(*UO, *SubExpr);
355 return;
356 }
357 case UO_Deref: {
358 const Expr *SubExpr = UO->getSubExpr();
359 killAndFlowOrigin(*UO, *SubExpr);
360 return;
361 }
362 default:
363 return;
364 }
365}
366
368 if (const Expr *RetExpr = RS->getRetValue()) {
369 if (OriginList *List = getOriginsList(*RetExpr))
370 for (OriginList *L = List; L != nullptr; L = L->peelOuterOrigin())
371 EscapesInCurrentBlock.push_back(FactMgr.createFact<ReturnEscapeFact>(
372 L->getOuterOriginID(), RetExpr));
373 }
374}
375
376void FactsGenerator::handleAssignment(const Expr *LHSExpr,
377 const Expr *RHSExpr) {
378 LHSExpr = LHSExpr->IgnoreParenImpCasts();
379 OriginList *LHSList = nullptr;
380
381 if (const auto *DRE_LHS = dyn_cast<DeclRefExpr>(LHSExpr)) {
382 LHSList = getOriginsList(*DRE_LHS);
383 assert(LHSList && "LHS is a DRE and should have an origin list");
384 }
385 // Handle assignment to member fields (e.g., `this->view = s` or `view = s`).
386 // This enables detection of dangling fields when local values escape to
387 // fields.
388 if (const auto *ME_LHS = dyn_cast<MemberExpr>(LHSExpr)) {
389 LHSList = getOriginsList(*ME_LHS);
390 assert(LHSList && "LHS is a MemberExpr and should have an origin list");
391 }
392 if (!LHSList)
393 return;
394 OriginList *RHSList = getOriginsList(*RHSExpr);
395 // For operator= with reference parameters (e.g.,
396 // `View& operator=(const View&)`), the RHS argument stays an lvalue,
397 // unlike built-in assignment where LValueToRValue cast strips the outer
398 // lvalue origin. Strip it manually to get the actual value origins being
399 // assigned.
400 RHSList = getRValueOrigins(RHSExpr, RHSList);
401
402 if (const auto *DRE_LHS = dyn_cast<DeclRefExpr>(LHSExpr)) {
403 QualType QT = DRE_LHS->getDecl()->getType();
404 if (QT->isReferenceType()) {
405 if (hasOrigins(QT->getPointeeType())) {
406 // Writing through a reference uses the binding but overwrites the
407 // pointee. Model this as a Read of the outer origin (keeping the
408 // binding live) and a Write of the inner origins (killing the pointee's
409 // liveness).
410 if (UseFact *UF = UseFacts.lookup(DRE_LHS)) {
411 const OriginList *FullList = UF->getUsedOrigins();
412 assert(FullList);
413 UF->setUsedOrigins(FactMgr.getOriginMgr().createSingleOriginList(
414 FullList->getOuterOriginID()));
415 if (const OriginList *InnerList = FullList->peelOuterOrigin()) {
416 UseFact *WriteUF = FactMgr.createFact<UseFact>(DRE_LHS, InnerList);
417 WriteUF->markAsWritten();
418 CurrentBlockFacts.push_back(WriteUF);
419 }
420 }
421 }
422 } else
423 markUseAsWrite(DRE_LHS);
424 }
425 if (!RHSList) {
426 // RHS has no tracked origins (e.g., assigning a callable without origins
427 // to std::function). Clear loans of the destination.
428 for (OriginList *LHSInner = LHSList->peelOuterOrigin(); LHSInner;
429 LHSInner = LHSInner->peelOuterOrigin())
430 CurrentBlockFacts.push_back(
431 FactMgr.createFact<KillOriginFact>(LHSInner->getOuterOriginID()));
432 return;
433 }
434 // Kill the old loans of the destination origin and flow the new loans
435 // from the source origin.
436 flow(LHSList->peelOuterOrigin(), RHSList, /*Kill=*/true);
437}
438
439void FactsGenerator::handlePointerArithmetic(const BinaryOperator *BO) {
440 if (Expr *RHS = BO->getRHS(); RHS->getType()->isPointerType()) {
441 killAndFlowOrigin(*BO, *RHS);
442 return;
443 }
444 Expr *LHS = BO->getLHS();
445 assert(LHS->getType()->isPointerType() &&
446 "Pointer arithmetic must have a pointer operand");
447 killAndFlowOrigin(*BO, *LHS);
448}
449
451 if (BO->isCompoundAssignmentOp())
452 return;
453 if (BO->getType()->isPointerType() && BO->isAdditiveOp())
454 handlePointerArithmetic(BO);
455 handleUse(BO->getRHS());
456 if (BO->isAssignmentOp())
457 handleAssignment(BO->getLHS(), BO->getRHS());
458 // TODO: Handle assignments involving dereference like `*p = q`.
459}
460
462 if (!hasOrigins(CO))
463 return;
464
465 const Expr *TrueExpr = CO->getTrueExpr();
466 const Expr *FalseExpr = CO->getFalseExpr();
467
468 const auto Preds = CurrentBlock->preds();
469
470 // Skip origin flow from conditional operator arms that cannot produce the
471 // result value: throw arms and calls to noreturn functions.
472 bool TBHasEdge = true;
473 bool FBHasEdge = true;
474
475 switch (CurrentBlock->pred_size()) {
476 case 0:
477 return;
478 case 1: {
479 TBHasEdge = llvm::any_of(**Preds.begin(),
480 [ExpectedStmt = TrueExpr->IgnoreParenImpCasts()](
481 const CFGElement &Elt) {
482 if (auto CS = Elt.getAs<CFGStmt>())
483 return CS->getStmt() == ExpectedStmt;
484 return false;
485 });
486 FBHasEdge = !TBHasEdge;
487 break;
488 }
489 case 2: {
490 const auto *It = Preds.begin();
491 TBHasEdge = It->isReachable();
492 FBHasEdge = (++It)->isReachable();
493 break;
494 }
495 default:
496 llvm_unreachable("expected at most 2 predecessors");
497 return;
498 }
499
500 bool FirstFlow = true;
501 auto HandleFlow = [&](const Expr *E) {
502 if (FirstFlow) {
503 killAndFlowOrigin(*CO, *E);
504 FirstFlow = false;
505 } else {
506 flowOrigin(*CO, *E);
507 }
508 };
509
510 if (TBHasEdge)
511 HandleFlow(TrueExpr);
512 if (FBHasEdge)
513 HandleFlow(FalseExpr);
514}
515
517 // Assignment operators have special "kill-then-propagate" semantics
518 // and are handled separately.
519 if (OCE->getOperator() == OO_Equal && OCE->getNumArgs() == 2 &&
520 hasOrigins(OCE->getArg(0)->getType())) {
521 // Pointer-like types: assignment inherently propagates origins.
522 QualType LHSTy = OCE->getArg(0)->getType();
523 if (LHSTy->isPointerOrReferenceType() || isGslPointerType(LHSTy) ||
524 isGslOwnerType(LHSTy)) {
525 handleAssignment(OCE->getArg(0), OCE->getArg(1));
526 return;
527 }
528 // Standard library callable wrappers (e.g., std::function) can propagate
529 // the stored lambda's origins.
530 if (const auto *RD = LHSTy->getAsCXXRecordDecl();
531 RD && isStdCallableWrapperType(RD)) {
532 handleAssignment(OCE->getArg(0), OCE->getArg(1));
533 return;
534 }
535 // Other tracked types: only defaulted operator= propagates origins.
536 // User-defined operator= has opaque semantics, so don't handle them now.
537 if (const auto *MD =
538 dyn_cast_or_null<CXXMethodDecl>(OCE->getDirectCallee());
539 MD && MD->isDefaulted()) {
540 handleAssignment(OCE->getArg(0), OCE->getArg(1));
541 return;
542 }
543 }
544
545 ArrayRef Args = {OCE->getArgs(), OCE->getNumArgs()};
546 // For `static operator()`, the first argument is the object argument,
547 // remove it from the argument list to avoid off-by-one errors.
548 if (OCE->getOperator() == OO_Call && OCE->getDirectCallee()->isStatic())
549 Args = Args.slice(1);
550 handleFunctionCall(OCE, OCE->getDirectCallee(), Args);
551}
552
554 const CXXFunctionalCastExpr *FCE) {
555 // Check if this is a test point marker. If so, we are done with this
556 // expression.
557 if (handleTestPoint(FCE))
558 return;
559 VisitCastExpr(FCE);
560}
561
563 if (!hasOrigins(ILE))
564 return;
565 // For list initialization with a single element, like `View{...}`, the
566 // origin of the list itself is the origin of its single element.
567 if (ILE->getNumInits() == 1)
568 killAndFlowOrigin(*ILE, *ILE->getInit(0));
569}
570
572 const CXXBindTemporaryExpr *BTE) {
573 killAndFlowOrigin(*BTE, *BTE->getSubExpr());
574}
575
577 const MaterializeTemporaryExpr *MTE) {
578 assert(MTE->isGLValue());
579 OriginList *MTEList = getOriginsList(*MTE);
580 if (!MTEList)
581 return;
582 OriginList *SubExprList = getOriginsList(*MTE->getSubExpr());
583 assert((!SubExprList ||
584 MTEList->getLength() == (SubExprList->getLength() + 1)) &&
585 "MTE top level origin should contain a loan to the MTE itself");
586
587 OriginList *RValMTEList = getRValueOrigins(MTE, MTEList);
588 flow(RValMTEList, SubExprList, /*Kill=*/true);
589 OriginID OuterMTEID = MTEList->getOuterOriginID();
591 // Issue a loan to MTE for the storage location represented by MTE.
592 const Loan *L = createLoan(FactMgr, MTE);
593 CurrentBlockFacts.push_back(
594 FactMgr.createFact<IssueFact>(L->getID(), OuterMTEID));
595 }
596}
597
599 // The lambda gets a single merged origin that aggregates all captured
600 // pointer-like origins. Currently we only need to detect whether the lambda
601 // outlives any capture.
602 OriginList *LambdaList = getOriginsList(*LE);
603 if (!LambdaList)
604 return;
605 bool Kill = true;
606 for (const Expr *Init : LE->capture_inits()) {
607 if (!Init)
608 continue;
609 OriginList *InitList = getOriginsList(*Init);
610 if (!InitList)
611 continue;
612 // FIXME: Consider flowing all origin levels once lambdas support more than
613 // one origin. Currently only the outermost origin is flowed, so by-ref
614 // captures like `[&p]` (where p is string_view) miss inner-level
615 // invalidation.
616 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
617 LambdaList->getOuterOriginID(), InitList->getOuterOriginID(), Kill));
618 Kill = false;
619 }
620}
621
623 assert(ASE->isGLValue() && "Array subscript should be a GL value");
624 OriginList *Dst = getOriginsList(*ASE);
625 assert(Dst && "Array subscript should have origins as it is a GL value");
626 OriginList *Src = getOriginsList(*ASE->getBase());
627 assert(Src && "Base of array subscript should have origins");
628 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
629 Dst->getOuterOriginID(), Src->getOuterOriginID(), /*Kill=*/true));
630}
631
633 OriginList *NewList = getOriginsList(*NE);
634 const Expr *Init = NE->getInitializer();
635
636 // Check if we have a placement new where the second argument is void*, to
637 // avoid flowing from non-pointer parameters, such as std::nothrow.
638 // And that the placement parameter num is 1,
639 // that is to mostly limit to standard library placement new.
640 if (NE->getNumPlacementArgs() == 1) {
641 if (const auto *Arg = NE->getOperatorNew()
642 ->getParamDecl(1)
643 ->getType()
644 ->getAs<PointerType>();
645 Arg && Arg->isVoidPointerType()) {
646 // Use the placement argument before the implicit conversion to void*, so
647 // inner origins are still available.
648 const Expr *PlacementArg = NE->getPlacementArg(0);
649 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(PlacementArg);
650 ICE && ICE->getCastKind() == CK_BitCast &&
651 PlacementArg->getType()->isVoidPointerType())
652 PlacementArg = ICE->getSubExpr();
653 OriginList *PlacementList = getOriginsList(*PlacementArg);
654 // FIXME: General placement arguments need separate handling to overwrite
655 // the right origins.
656
657 // The pointer returned by placement new comes from the placement
658 // argument.
659 if (PlacementList)
660 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
661 NewList->getOuterOriginID(), PlacementList->getOuterOriginID(),
662 true));
663 }
664 } else {
665 const Loan *L = createLoan(FactMgr, NE);
666 CurrentBlockFacts.push_back(
667 FactMgr.createFact<IssueFact>(L->getID(), NewList->getOuterOriginID()));
668 }
669
670 NewList = NewList->peelOuterOrigin();
671
672 if (!NewList || !Init)
673 return;
674
675 // FIXME: OriginList is null for `new[]` initializers. Remove this `Init`
676 // check once array origins are supported.
677 if (OriginList *InitList = getOriginsList(*Init); InitList)
678 flow(NewList, InitList, true);
679}
680
682 OriginList *List = getOriginsList(*DE->getArgument());
683 CurrentBlockFacts.push_back(
684 FactMgr.createFact<InvalidateOriginFact>(List->getOuterOriginID(), DE));
685}
686
687bool FactsGenerator::escapesViaReturn(OriginID OID) const {
688 return llvm::any_of(EscapesInCurrentBlock, [OID](const Fact *F) {
689 if (const auto *EF = F->getAs<ReturnEscapeFact>())
690 return EF->getEscapedOriginID() == OID;
691 return false;
692 });
693}
694
695void FactsGenerator::handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds) {
696 const VarDecl *LifetimeEndsVD = LifetimeEnds.getVarDecl();
697 if (!LifetimeEndsVD)
698 return;
699 // Expire the origin when its variable's lifetime ends to ensure liveness
700 // doesn't persist through loop back-edges.
701 std::optional<OriginID> ExpiredOID;
702 if (OriginList *List = getOriginsList(*LifetimeEndsVD)) {
703 OriginID OID = List->getOuterOriginID();
704 // Skip origins that escape via return; the escape checker needs their loans
705 // to remain until the return statement is processed.
706 if (!escapesViaReturn(OID))
707 ExpiredOID = OID;
708 }
709 CurrentBlockFacts.push_back(FactMgr.createFact<ExpireFact>(
710 AccessPath(LifetimeEndsVD), LifetimeEnds.getTriggerStmt()->getEndLoc(),
711 ExpiredOID));
712}
713
714void FactsGenerator::handleFullExprCleanup(
715 const CFGFullExprCleanup &FullExprCleanup) {
716 for (const auto *MTE : FullExprCleanup.getExpiringMTEs())
717 CurrentBlockFacts.push_back(
718 FactMgr.createFact<ExpireFact>(AccessPath(MTE), MTE->getEndLoc()));
719}
720
721void FactsGenerator::handleExitBlock() {
722 for (const Origin &O : FactMgr.getOriginMgr().getOrigins())
723 if (auto *FD = dyn_cast_if_present<FieldDecl>(O.getDecl()))
724 // Create FieldEscapeFacts for all field origins that remain live at exit.
725 EscapesInCurrentBlock.push_back(
726 FactMgr.createFact<FieldEscapeFact>(O.ID, FD));
727 else if (auto *VD = dyn_cast_if_present<VarDecl>(O.getDecl())) {
728 // Create GlobalEscapeFacts for all origins with global-storage that
729 // remain live at exit.
730 if (VD->hasGlobalStorage()) {
731 EscapesInCurrentBlock.push_back(
732 FactMgr.createFact<GlobalEscapeFact>(O.ID, VD));
733 }
734 }
735}
736
737void FactsGenerator::handleGSLPointerConstruction(const CXXConstructExpr *CCE) {
738 assert(isGslPointerType(CCE->getType()));
739 if (CCE->getNumArgs() != 1)
740 return;
741
742 const Expr *Arg = CCE->getArg(0);
743 if (isGslPointerType(Arg->getType())) {
744 OriginList *ArgList = getOriginsList(*Arg);
745 assert(ArgList && "GSL pointer argument should have an origin list");
746 // GSL pointer is constructed from another gsl pointer.
747 // Example:
748 // View(View v);
749 // View(const View &v);
750 ArgList = getRValueOrigins(Arg, ArgList);
751 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
752 } else if (Arg->getType()->isPointerType()) {
753 // GSL pointer is constructed from a raw pointer. Flow only the outermost
754 // raw pointer. Example:
755 // View(const char*);
756 // Span<int*>(const in**);
757 OriginList *ArgList = getOriginsList(*Arg);
758 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
759 getOriginsList(*CCE)->getOuterOriginID(), ArgList->getOuterOriginID(),
760 /*Kill=*/true));
761 } else {
762 // This could be a new borrow.
763 // TODO: Add code example here.
764 handleFunctionCall(CCE, CCE->getConstructor(),
765 {CCE->getArgs(), CCE->getNumArgs()},
766 /*IsGslConstruction=*/true);
767 }
768}
769
770void FactsGenerator::handleMovedArgsInCall(const FunctionDecl *FD,
771 ArrayRef<const Expr *> Args) {
772 unsigned IsInstance = 0;
773 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
774 MD && MD->isInstance() && !isa<CXXConstructorDecl>(FD)) {
775 IsInstance = 1;
776 // std::unique_ptr::release() transfers ownership.
777 // Treat it as a move to prevent false-positive warnings when the unique_ptr
778 // destructor runs after ownership has been transferred.
779 if (isUniquePtrRelease(*MD)) {
780 const Expr *UniquePtrExpr = Args[0];
781 OriginList *MovedOrigins = getOriginsList(*UniquePtrExpr);
782 if (MovedOrigins)
783 CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>(
784 UniquePtrExpr, MovedOrigins->getOuterOriginID()));
785 }
786 }
787
788 // Skip 'this' arg as it cannot be moved.
789 for (unsigned I = IsInstance;
790 I < Args.size() && I < FD->getNumParams() + IsInstance; ++I) {
791 const ParmVarDecl *PVD = FD->getParamDecl(I - IsInstance);
792 if (!PVD->getType()->isRValueReferenceType())
793 continue;
794 const Expr *Arg = Args[I];
795 OriginList *MovedOrigins = getOriginsList(*Arg);
796 assert(MovedOrigins->getLength() >= 1 &&
797 "unexpected length for r-value reference param");
798 // Arg is being moved to this parameter. Mark the origin as moved.
799 CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>(
800 Arg, MovedOrigins->getOuterOriginID()));
801 }
802}
803
804void FactsGenerator::handleInvalidatingCall(const Expr *Call,
805 const FunctionDecl *FD,
806 ArrayRef<const Expr *> Args) {
807 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
808 if (!MD || !MD->isInstance())
809 return;
810
811 if (!isInvalidationMethod(*MD))
812 return;
813 // Heuristics to turn-down false positives.
814 auto *DRE = dyn_cast<DeclRefExpr>(Args[0]);
815 if (!DRE || DRE->getDecl()->getType()->isReferenceType())
816 return;
817
818 OriginList *ThisList = getOriginsList(*Args[0]);
819 if (ThisList)
820 CurrentBlockFacts.push_back(FactMgr.createFact<InvalidateOriginFact>(
821 ThisList->getOuterOriginID(), Call));
822}
823
824void FactsGenerator::handleDestructiveCall(const Expr *Call,
825 const FunctionDecl *FD,
826 ArrayRef<const Expr *> Args) {
827 if (!destructsFirstArg(*FD))
828 return;
829 OriginList *ArgList = getOriginsList(*Args[0]);
830 if (ArgList)
831 CurrentBlockFacts.push_back(FactMgr.createFact<InvalidateOriginFact>(
832 ArgList->getOuterOriginID(), Call));
833}
834
835void FactsGenerator::handleImplicitObjectFieldUses(const Expr *Call,
836 const FunctionDecl *FD) {
837 const auto *MemberCall = dyn_cast_or_null<CXXMemberCallExpr>(Call);
838 if (!MemberCall)
839 return;
840
841 if (!isa_and_present<CXXThisExpr>(
842 MemberCall->getImplicitObjectArgument()->IgnoreImpCasts()))
843 return;
844
845 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
846 assert(MD && "Function must be a CXXMethodDecl for member calls");
847
848 const auto *ClassDecl = MD->getParent()->getDefinition();
849 if (!ClassDecl)
850 return;
851
852 const auto UseFields = [&](const CXXRecordDecl *RD) {
853 for (const auto *Field : RD->fields())
854 if (auto *FieldList = getOriginsList(*Field))
855 CurrentBlockFacts.push_back(
856 FactMgr.createFact<UseFact>(Call, FieldList));
857 };
858
859 UseFields(ClassDecl);
860
861 ClassDecl->forallBases([&](const CXXRecordDecl *Base) {
862 UseFields(Base);
863 return true;
864 });
865}
866
867void FactsGenerator::handleFunctionCall(const Expr *Call,
868 const FunctionDecl *FD,
869 ArrayRef<const Expr *> Args,
870 bool IsGslConstruction) {
871 OriginList *CallList = getOriginsList(*Call);
872 // Ignore functions returning values with no origin.
874 if (!FD)
875 return;
876 // All arguments to a function are a use of the corresponding expressions.
877 for (const Expr *Arg : Args)
878 handleUse(Arg);
879 handleInvalidatingCall(Call, FD, Args);
880 handleDestructiveCall(Call, FD, Args);
881 handleMovedArgsInCall(FD, Args);
882 handleImplicitObjectFieldUses(Call, FD);
883 if (!CallList)
884 return;
885 auto IsArgLifetimeBound = [FD](unsigned I) -> bool {
886 const ParmVarDecl *PVD = nullptr;
887 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD);
888 Method && Method->isInstance() && !isa<CXXConstructorDecl>(FD)) {
889 if (I == 0)
890 // For the 'this' argument, the attribute is on the method itself.
893 Method, /*RunningUnderLifetimeSafety=*/true);
894 if ((I - 1) < Method->getNumParams())
895 // For explicit arguments, find the corresponding parameter
896 // declaration.
897 PVD = Method->getParamDecl(I - 1);
898 } else if (I == 0 && shouldTrackFirstArgument(FD)) {
899 return true;
900 } else if (I == 1 && shouldTrackSecondArgument(FD)) {
901 return true;
902 } else if (I < FD->getNumParams()) {
903 // For free functions or static methods.
904 PVD = FD->getParamDecl(I);
905 }
906 return PVD ? PVD->hasAttr<clang::LifetimeBoundAttr>() : false;
907 };
908 auto shouldTrackPointerImplicitObjectArg = [FD](unsigned I) -> bool {
909 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
910 if (!Method || !Method->isInstance())
911 return false;
912 return I == 0 &&
913 isGslPointerType(Method->getFunctionObjectParameterType()) &&
915 /*RunningUnderLifetimeSafety=*/true);
916 };
917 if (Args.empty())
918 return;
919 bool KillSrc = true;
920 for (unsigned I = 0; I < Args.size(); ++I) {
921 OriginList *ArgList = getOriginsList(*Args[I]);
922 if (!ArgList)
923 continue;
924 if (IsGslConstruction) {
925 // TODO: document with code example.
926 // std::string_view(const std::string_view& from)
927 if (isGslPointerType(Args[I]->getType())) {
928 assert(!Args[I]->isGLValue() || ArgList->getLength() >= 2);
929 ArgList = getRValueOrigins(Args[I], ArgList);
930 }
931 if (isGslOwnerType(Args[I]->getType())) {
932 // The constructed gsl::Pointer borrows from the Owner's storage, not
933 // from what the Owner itself borrows, so only the outermost origin is
934 // needed.
935 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
936 CallList->getOuterOriginID(), ArgList->getOuterOriginID(),
937 KillSrc));
938 KillSrc = false;
939 } else if (IsArgLifetimeBound(I)) {
940 // Only flow the outer origin here. For lifetimebound args in
941 // gsl::Pointer construction, we do not have enough information to
942 // safely match inner origins, so the source and
943 // destination origin lists may have different lengths.
944 // FIXME: Handle origin-shape mismatches gracefully so we can also flow
945 // inner origins.
946 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
947 CallList->getOuterOriginID(), ArgList->getOuterOriginID(),
948 KillSrc));
949 KillSrc = false;
950 }
951 } else if (shouldTrackPointerImplicitObjectArg(I)) {
952 assert(ArgList->getLength() >= 2 &&
953 "Object arg of pointer type should have atleast two origins");
954 // See through the GSLPointer reference to see the pointer's value.
955 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
956 CallList->getOuterOriginID(),
957 ArgList->peelOuterOrigin()->getOuterOriginID(), KillSrc));
958 KillSrc = false;
959 } else if (IsArgLifetimeBound(I)) {
960 // Lifetimebound on a non-GSL-ctor function means the returned
961 // pointer/reference itself must not outlive the arguments. This
962 // only constraints the top-level origin.
963 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
964 CallList->getOuterOriginID(), ArgList->getOuterOriginID(), KillSrc));
965 KillSrc = false;
966 }
967 }
968}
969
970/// Checks if the expression is a `void("__lifetime_test_point_...")` cast.
971/// If so, creates a `TestPointFact` and returns true.
972bool FactsGenerator::handleTestPoint(const CXXFunctionalCastExpr *FCE) {
973 if (!FCE->getType()->isVoidType())
974 return false;
975
976 const auto *SubExpr = FCE->getSubExpr()->IgnoreParenImpCasts();
977 if (const auto *SL = dyn_cast<StringLiteral>(SubExpr)) {
978 llvm::StringRef LiteralValue = SL->getString();
979 const std::string Prefix = "__lifetime_test_point_";
980
981 if (LiteralValue.starts_with(Prefix)) {
982 StringRef Annotation = LiteralValue.drop_front(Prefix.length());
983 CurrentBlockFacts.push_back(
984 FactMgr.createFact<TestPointFact>(Annotation));
985 return true;
986 }
987 }
988 return false;
989}
990
991void FactsGenerator::handleUse(const Expr *E) {
992 OriginList *List = getOriginsList(*E);
993 if (!List)
994 return;
995 // For DeclRefExpr: Remove the outer layer of origin which borrows from the
996 // decl directly (e.g., when this is not a reference). This is a use of the
997 // underlying decl.
998 if (auto *DRE = dyn_cast<DeclRefExpr>(E);
999 DRE && !DRE->getDecl()->getType()->isReferenceType())
1000 List = getRValueOrigins(DRE, List);
1001 // Skip if there is no inner origin (e.g., when it is not a pointer type).
1002 if (!List)
1003 return;
1004 if (!UseFacts.contains(E)) {
1005 UseFact *UF = FactMgr.createFact<UseFact>(E, List);
1006 CurrentBlockFacts.push_back(UF);
1007 UseFacts[E] = UF;
1008 }
1009}
1010
1011void FactsGenerator::markUseAsWrite(const DeclRefExpr *DRE) {
1012 if (UseFacts.contains(DRE))
1013 UseFacts[DRE]->markAsWritten();
1014}
1015
1016// Creates an IssueFact for a new placeholder loan for each pointer or reference
1017// parameter at the function's entry.
1018llvm::SmallVector<Fact *> FactsGenerator::issuePlaceholderLoans() {
1019 const auto *FD = dyn_cast<FunctionDecl>(AC.getDecl());
1020 if (!FD)
1021 return {};
1022
1023 llvm::SmallVector<Fact *> PlaceholderLoanFacts;
1024 if (auto ThisOrigins = FactMgr.getOriginMgr().getThisOrigins()) {
1025 OriginList *List = *ThisOrigins;
1026 const Loan *L = FactMgr.getLoanMgr().createLoan(
1028 /*IssuingExpr=*/nullptr);
1029 PlaceholderLoanFacts.push_back(
1030 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
1031 }
1032 for (const ParmVarDecl *PVD : FD->parameters()) {
1033 OriginList *List = getOriginsList(*PVD);
1034 if (!List)
1035 continue;
1036 const Loan *L = FactMgr.getLoanMgr().createLoan(
1037 AccessPath::Placeholder(PVD), /*IssuingExpr=*/nullptr);
1038 PlaceholderLoanFacts.push_back(
1039 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
1040 }
1041 return PlaceholderLoanFacts;
1042}
1043
1044} // namespace clang::lifetimes::internal
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Defines an enumeration for C++ overloaded operators.
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2724
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
Expr * getLHS() const
Definition Expr.h:4091
Expr * getRHS() const
Definition Expr.h:4093
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4127
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4177
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
Represents a single basic block in a source-level CFG.
Definition CFG.h:632
Represents a top-level expression in a basic block.
Definition CFG.h:55
std::optional< T > getAs() const
Convert to the specified CFGElement type, returning std::nullopt if this CFGElement is not of the des...
Definition CFG.h:110
Represents C++ base or member initializer from constructor's initialization list.
Definition CFG.h:229
Represents the point where the lifetime of an automatic object ends.
Definition CFG.h:294
const Stmt * getTriggerStmt() const
Definition CFG.h:303
const VarDecl * getVarDecl() const
Definition CFG.h:299
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1250
CFGBlock & getExit()
Definition CFG.h:1366
CFGBlock & getEntry()
Definition CFG.h:1364
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3071
Represents a C++ base or member initializer.
Definition DeclCXX.h:2385
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2587
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2531
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1107
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr....
Definition ExprCXX.h:1835
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:743
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:724
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:115
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3140
Decl * getCalleeDecl()
Definition Expr.h:3123
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3679
CastKind getCastKind() const
Definition Expr.h:3723
Expr * getSubExpr()
Definition Expr.h:3729
ConditionalOperator - The ?
Definition Expr.h:4394
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4426
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4421
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1384
ValueDecl * getDecl()
Definition Expr.h:1341
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1637
decl_range decls()
Definition Stmt.h:1685
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition DeclBase.h:1132
This represents one expression.
Definition Expr.h:112
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3178
bool isStatic() const
Definition Decl.h:2947
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2403
Describes an C or C++ initializer list.
Definition Expr.h:5302
unsigned getNumInits() const
Definition Expr.h:5332
const Expr * getInit(unsigned Init) const
Definition Expr.h:5354
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
Expr * getBase() const
Definition Expr.h:3444
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3383
A (possibly-)qualified type.
Definition TypeBase.h:937
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3166
Expr * getRetValue()
Definition Stmt.h:3193
RetTy Visit(PTR(Stmt) S, ParamTys... P)
Definition StmtVisitor.h:45
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isVoidPointerType() const
Definition Type.cpp:749
bool isPointerType() const
Definition TypeBase.h:8673
bool isReferenceType() const
Definition TypeBase.h:8697
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isPointerOrReferenceType() const
Definition TypeBase.h:8677
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:924
Represents the storage location being borrowed, e.g., a specific stack variable or a field within it:...
Definition Loans.h:45
static AccessPath Placeholder(const ParmVarDecl *PVD)
Definition Loans.h:64
FactType * createFact(Args &&...args)
Definition Facts.h:355
An abstract base class for a single, atomic lifetime-relevant event.
Definition Facts.h:34
const T * getAs() const
Definition Facts.h:76
void VisitDeclRefExpr(const DeclRefExpr *DRE)
void VisitBinaryOperator(const BinaryOperator *BO)
void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *MTE)
void VisitCXXConstructExpr(const CXXConstructExpr *CCE)
void VisitCXXDeleteExpr(const CXXDeleteExpr *DE)
void VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *FCE)
void VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *DIE)
void VisitInitListExpr(const InitListExpr *ILE)
void VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *N)
void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE)
void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE)
void VisitUnaryOperator(const UnaryOperator *UO)
void VisitConditionalOperator(const ConditionalOperator *CO)
void VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE)
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE)
Represents that an origin's storage has been invalidated by a container operation (e....
Definition Facts.h:264
Loan * createLoan(AccessPath Path, const Expr *IssueExpr)
Definition Loans.h:143
Represents lending a storage location.
Definition Loans.h:122
A list of origins representing levels of indirection for pointer-like types.
Definition Origins.h:95
OriginList * peelOuterOrigin() const
Definition Origins.h:99
OriginList * createSingleOriginList(OriginID OID)
Wraps an existing OriginID in a new single-element OriginList, so a fact can refer to a single level ...
Definition Origins.cpp:189
Represents that an origin escapes via a return statement.
Definition Facts.h:181
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
static OriginList * getRValueOrigins(const Expr *E, OriginList *List)
Simulates LValueToRValue conversion by peeling the outer lvalue origin if the expression is a GLValue...
bool doesDeclHaveStorage(const ValueDecl *D)
Returns true if the declaration has its own storage that can be borrowed.
Definition Origins.cpp:156
static const Loan * createLoan(FactManager &FactMgr, const DeclRefExpr *DRE)
Creates a loan for the storage path of a given declaration reference.
bool isGslPointerType(QualType QT)
bool isStdCallableWrapperType(const CXXRecordDecl *RD)
bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee, bool RunningUnderLifetimeSafety)
bool shouldTrackFirstArgument(const FunctionDecl *FD)
bool isUniquePtrRelease(const CXXMethodDecl &MD)
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
const FunctionDecl * getDeclWithMergedLifetimeBoundAttrs(const FunctionDecl *FD)
bool isInvalidationMethod(const CXXMethodDecl &MD)
bool destructsFirstArg(const FunctionDecl &FD)
bool isGslOwnerType(QualType QT)
bool shouldTrackSecondArgument(const FunctionDecl *FD)
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
U cast(CodeGen::Address addr)
Definition Address.h:327
llvm::Expected< Stmt * > ExpectedStmt
#define false
Definition stdbool.h:26