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 *TargetExpr,
377 const Expr *LHSExpr,
378 const Expr *RHSExpr) {
379 LHSExpr = LHSExpr->IgnoreParenImpCasts();
380 OriginList *LHSList = nullptr;
381
382 if (const auto *DRE_LHS = dyn_cast<DeclRefExpr>(LHSExpr)) {
383 LHSList = getOriginsList(*DRE_LHS);
384 assert(LHSList && "LHS is a DRE and should have an origin list");
385 }
386 // Handle assignment to member fields (e.g., `this->view = s` or `view = s`).
387 // This enables detection of dangling fields when local values escape to
388 // fields.
389 if (const auto *ME_LHS = dyn_cast<MemberExpr>(LHSExpr)) {
390 LHSList = getOriginsList(*ME_LHS);
391 assert(LHSList && "LHS is a MemberExpr and should have an origin list");
392 }
393 if (!LHSList)
394 return;
395 OriginList *RHSList = getOriginsList(*RHSExpr);
396 // For operator= with reference parameters (e.g.,
397 // `View& operator=(const View&)`), the RHS argument stays an lvalue,
398 // unlike built-in assignment where LValueToRValue cast strips the outer
399 // lvalue origin. Strip it manually to get the actual value origins being
400 // assigned.
401 RHSList = getRValueOrigins(RHSExpr, RHSList);
402
403 if (const auto *DRE_LHS = dyn_cast<DeclRefExpr>(LHSExpr)) {
404 QualType QT = DRE_LHS->getDecl()->getType();
405 if (QT->isReferenceType()) {
406 if (hasOrigins(QT->getPointeeType())) {
407 // Writing through a reference uses the binding but overwrites the
408 // pointee. Model this as a Read of the outer origin (keeping the
409 // binding live) and a Write of the inner origins (killing the pointee's
410 // liveness).
411 if (UseFact *UF = UseFacts.lookup(DRE_LHS)) {
412 const OriginList *FullList = UF->getUsedOrigins();
413 assert(FullList);
414 UF->setUsedOrigins(FactMgr.getOriginMgr().createSingleOriginList(
415 FullList->getOuterOriginID()));
416 if (const OriginList *InnerList = FullList->peelOuterOrigin()) {
417 UseFact *WriteUF = FactMgr.createFact<UseFact>(DRE_LHS, InnerList);
418 WriteUF->markAsWritten();
419 CurrentBlockFacts.push_back(WriteUF);
420 }
421 }
422 }
423 } else
424 markUseAsWrite(DRE_LHS);
425 }
426 if (!RHSList) {
427 // RHS has no tracked origins (e.g., assigning a callable without origins
428 // to std::function). Clear loans of the destination.
429 for (OriginList *LHSInner = LHSList->peelOuterOrigin(); LHSInner;
430 LHSInner = LHSInner->peelOuterOrigin())
431 CurrentBlockFacts.push_back(
432 FactMgr.createFact<KillOriginFact>(LHSInner->getOuterOriginID()));
433 return;
434 }
435 // Kill the old loans of the destination origin and flow the new loans
436 // from the source origin.
437 flow(LHSList->peelOuterOrigin(), RHSList, /*Kill=*/true);
438 killAndFlowOrigin(*TargetExpr, *LHSExpr);
439}
440
441void FactsGenerator::handlePointerArithmetic(const BinaryOperator *BO) {
442 if (Expr *RHS = BO->getRHS(); RHS->getType()->isPointerType()) {
443 killAndFlowOrigin(*BO, *RHS);
444 return;
445 }
446 Expr *LHS = BO->getLHS();
447 assert(LHS->getType()->isPointerType() &&
448 "Pointer arithmetic must have a pointer operand");
449 killAndFlowOrigin(*BO, *LHS);
450}
451
453 if (BO->isCompoundAssignmentOp())
454 return;
455 if (BO->getType()->isPointerType() && BO->isAdditiveOp())
456 handlePointerArithmetic(BO);
457 handleUse(BO->getRHS());
458 if (BO->isAssignmentOp())
459 handleAssignment(BO, BO->getLHS(), BO->getRHS());
460 // TODO: Handle assignments involving dereference like `*p = q`.
461}
462
464 if (!hasOrigins(CO))
465 return;
466
467 const Expr *TrueExpr = CO->getTrueExpr();
468 const Expr *FalseExpr = CO->getFalseExpr();
469
470 const auto Preds = CurrentBlock->preds();
471
472 // Skip origin flow from conditional operator arms that cannot produce the
473 // result value: throw arms and calls to noreturn functions.
474 bool TBHasEdge = true;
475 bool FBHasEdge = true;
476
477 switch (CurrentBlock->pred_size()) {
478 case 0:
479 return;
480 case 1: {
481 TBHasEdge = llvm::any_of(**Preds.begin(),
482 [ExpectedStmt = TrueExpr->IgnoreParenImpCasts()](
483 const CFGElement &Elt) {
484 if (auto CS = Elt.getAs<CFGStmt>())
485 return CS->getStmt() == ExpectedStmt;
486 return false;
487 });
488 FBHasEdge = !TBHasEdge;
489 break;
490 }
491 case 2: {
492 const auto *It = Preds.begin();
493 TBHasEdge = It->isReachable();
494 FBHasEdge = (++It)->isReachable();
495 break;
496 }
497 default:
498 llvm_unreachable("expected at most 2 predecessors");
499 return;
500 }
501
502 bool FirstFlow = true;
503 auto HandleFlow = [&](const Expr *E) {
504 if (FirstFlow) {
505 killAndFlowOrigin(*CO, *E);
506 FirstFlow = false;
507 } else {
508 flowOrigin(*CO, *E);
509 }
510 };
511
512 if (TBHasEdge)
513 HandleFlow(TrueExpr);
514 if (FBHasEdge)
515 HandleFlow(FalseExpr);
516}
517
519 // Assignment operators have special "kill-then-propagate" semantics
520 // and are handled separately.
521 if (OCE->getOperator() == OO_Equal && OCE->getNumArgs() == 2 &&
522 hasOrigins(OCE->getArg(0)->getType())) {
523 // Pointer-like types: assignment inherently propagates origins.
524 QualType LHSTy = OCE->getArg(0)->getType();
525 if (LHSTy->isPointerOrReferenceType() || isGslPointerType(LHSTy) ||
526 isGslOwnerType(LHSTy)) {
527 handleAssignment(OCE, OCE->getArg(0), OCE->getArg(1));
528 return;
529 }
530 // Standard library callable wrappers (e.g., std::function) can propagate
531 // the stored lambda's origins.
532 if (const auto *RD = LHSTy->getAsCXXRecordDecl();
533 RD && isStdCallableWrapperType(RD)) {
534 handleAssignment(OCE, OCE->getArg(0), OCE->getArg(1));
535 return;
536 }
537 // Other tracked types: only defaulted operator= propagates origins.
538 // User-defined operator= has opaque semantics, so don't handle them now.
539 if (const auto *MD =
540 dyn_cast_or_null<CXXMethodDecl>(OCE->getDirectCallee());
541 MD && MD->isDefaulted()) {
542 handleAssignment(OCE, OCE->getArg(0), OCE->getArg(1));
543 return;
544 }
545 }
546
547 ArrayRef Args = {OCE->getArgs(), OCE->getNumArgs()};
548 // For `static operator()`, the first argument is the object argument,
549 // remove it from the argument list to avoid off-by-one errors.
550 if (OCE->getOperator() == OO_Call && OCE->getDirectCallee()->isStatic())
551 Args = Args.slice(1);
552 handleFunctionCall(OCE, OCE->getDirectCallee(), Args);
553}
554
556 const CXXFunctionalCastExpr *FCE) {
557 // Check if this is a test point marker. If so, we are done with this
558 // expression.
559 if (handleTestPoint(FCE))
560 return;
561 VisitCastExpr(FCE);
562}
563
565 if (!hasOrigins(ILE))
566 return;
567 // For list initialization with a single element, like `View{...}`, the
568 // origin of the list itself is the origin of its single element.
569 if (ILE->getNumInits() == 1)
570 killAndFlowOrigin(*ILE, *ILE->getInit(0));
571}
572
574 const CXXBindTemporaryExpr *BTE) {
575 killAndFlowOrigin(*BTE, *BTE->getSubExpr());
576}
577
579 const MaterializeTemporaryExpr *MTE) {
580 assert(MTE->isGLValue());
581 OriginList *MTEList = getOriginsList(*MTE);
582 if (!MTEList)
583 return;
584 OriginList *SubExprList = getOriginsList(*MTE->getSubExpr());
585 assert((!SubExprList ||
586 MTEList->getLength() == (SubExprList->getLength() + 1)) &&
587 "MTE top level origin should contain a loan to the MTE itself");
588
589 OriginList *RValMTEList = getRValueOrigins(MTE, MTEList);
590 flow(RValMTEList, SubExprList, /*Kill=*/true);
591 OriginID OuterMTEID = MTEList->getOuterOriginID();
593 // Issue a loan to MTE for the storage location represented by MTE.
594 const Loan *L = createLoan(FactMgr, MTE);
595 CurrentBlockFacts.push_back(
596 FactMgr.createFact<IssueFact>(L->getID(), OuterMTEID));
597 }
598}
599
601 // The lambda gets a single merged origin that aggregates all captured
602 // pointer-like origins. Currently we only need to detect whether the lambda
603 // outlives any capture.
604 OriginList *LambdaList = getOriginsList(*LE);
605 if (!LambdaList)
606 return;
607 bool Kill = true;
608 for (const Expr *Init : LE->capture_inits()) {
609 if (!Init)
610 continue;
611 OriginList *InitList = getOriginsList(*Init);
612 if (!InitList)
613 continue;
614 // FIXME: Consider flowing all origin levels once lambdas support more than
615 // one origin. Currently only the outermost origin is flowed, so by-ref
616 // captures like `[&p]` (where p is string_view) miss inner-level
617 // invalidation.
618 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
619 LambdaList->getOuterOriginID(), InitList->getOuterOriginID(), Kill));
620 Kill = false;
621 }
622}
623
625 assert(ASE->isGLValue() && "Array subscript should be a GL value");
626 OriginList *Dst = getOriginsList(*ASE);
627 assert(Dst && "Array subscript should have origins as it is a GL value");
628 OriginList *Src = getOriginsList(*ASE->getBase());
629 assert(Src && "Base of array subscript should have origins");
630 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
631 Dst->getOuterOriginID(), Src->getOuterOriginID(), /*Kill=*/true));
632}
633
634void FactsGenerator::handlePlacementNew(const CXXNewExpr *NE,
635 OriginList *NewList) {
636 // Model only the standard single-argument placement new form, where the
637 // placement argument corresponds to a void* allocation-function parameter.
638 // Other placement forms, such as std::nothrow, are not modeled as providing
639 // storage for the returned pointer.
640 if (NE->getNumPlacementArgs() != 1)
641 return;
642
643 const FunctionDecl *OperatorNew = NE->getOperatorNew();
644 if (OperatorNew->getNumParams() <= 1)
645 return;
646
647 const auto *Arg =
648 OperatorNew->getParamDecl(1)->getType()->getAs<PointerType>();
649 if (!Arg || !Arg->isVoidPointerType())
650 return;
651
652 // Use the placement argument before the implicit conversion to void*, so
653 // inner origins are still available.
654 const Expr *PlacementArg = NE->getPlacementArg(0);
655 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(PlacementArg);
656 ICE && ICE->getCastKind() == CK_BitCast &&
657 PlacementArg->getType()->isVoidPointerType())
658 PlacementArg = ICE->getSubExpr();
659 OriginList *PlacementList = getOriginsList(*PlacementArg);
660 // FIXME: General placement arguments need separate handling to overwrite
661 // the right origins.
662
663 // The pointer returned by placement new comes from the placement
664 // argument.
665 if (PlacementList)
666 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
667 NewList->getOuterOriginID(), PlacementList->getOuterOriginID(), true));
668}
669
671 OriginList *NewList = getOriginsList(*NE);
672 const Expr *Init = NE->getInitializer();
673
674 if (NE->getNumPlacementArgs() == 1) {
675 handlePlacementNew(NE, NewList);
676 } else {
677 const Loan *L = createLoan(FactMgr, NE);
678 CurrentBlockFacts.push_back(
679 FactMgr.createFact<IssueFact>(L->getID(), NewList->getOuterOriginID()));
680 }
681
682 NewList = NewList->peelOuterOrigin();
683
684 if (!NewList || !Init)
685 return;
686
687 // FIXME: OriginList is null for `new[]` initializers. Remove this `Init`
688 // check once array origins are supported.
689 if (OriginList *InitList = getOriginsList(*Init); InitList)
690 flow(NewList, InitList, true);
691}
692
694 OriginList *List = getOriginsList(*DE->getArgument());
695 CurrentBlockFacts.push_back(
696 FactMgr.createFact<InvalidateOriginFact>(List->getOuterOriginID(), DE));
697}
698
699bool FactsGenerator::escapesViaReturn(OriginID OID) const {
700 return llvm::any_of(EscapesInCurrentBlock, [OID](const Fact *F) {
701 if (const auto *EF = F->getAs<ReturnEscapeFact>())
702 return EF->getEscapedOriginID() == OID;
703 return false;
704 });
705}
706
707void FactsGenerator::handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds) {
708 const VarDecl *LifetimeEndsVD = LifetimeEnds.getVarDecl();
709 if (!LifetimeEndsVD)
710 return;
711 // Expire the origin when its variable's lifetime ends to ensure liveness
712 // doesn't persist through loop back-edges.
713 std::optional<OriginID> ExpiredOID;
714 if (OriginList *List = getOriginsList(*LifetimeEndsVD)) {
715 OriginID OID = List->getOuterOriginID();
716 // Skip origins that escape via return; the escape checker needs their loans
717 // to remain until the return statement is processed.
718 if (!escapesViaReturn(OID))
719 ExpiredOID = OID;
720 }
721 CurrentBlockFacts.push_back(FactMgr.createFact<ExpireFact>(
722 AccessPath(LifetimeEndsVD), LifetimeEnds.getTriggerStmt()->getEndLoc(),
723 ExpiredOID));
724}
725
726void FactsGenerator::handleFullExprCleanup(
727 const CFGFullExprCleanup &FullExprCleanup) {
728 for (const auto *MTE : FullExprCleanup.getExpiringMTEs())
729 CurrentBlockFacts.push_back(
730 FactMgr.createFact<ExpireFact>(AccessPath(MTE), MTE->getEndLoc()));
731}
732
733void FactsGenerator::handleExitBlock() {
734 for (const Origin &O : FactMgr.getOriginMgr().getOrigins())
735 if (auto *FD = dyn_cast_if_present<FieldDecl>(O.getDecl()))
736 // Create FieldEscapeFacts for all field origins that remain live at exit.
737 EscapesInCurrentBlock.push_back(
738 FactMgr.createFact<FieldEscapeFact>(O.ID, FD));
739 else if (auto *VD = dyn_cast_if_present<VarDecl>(O.getDecl())) {
740 // Create GlobalEscapeFacts for all origins with global-storage that
741 // remain live at exit.
742 if (VD->hasGlobalStorage()) {
743 EscapesInCurrentBlock.push_back(
744 FactMgr.createFact<GlobalEscapeFact>(O.ID, VD));
745 }
746 }
747}
748
749void FactsGenerator::handleGSLPointerConstruction(const CXXConstructExpr *CCE) {
750 assert(isGslPointerType(CCE->getType()));
751 if (CCE->getNumArgs() != 1)
752 return;
753
754 const Expr *Arg = CCE->getArg(0);
755 if (isGslPointerType(Arg->getType())) {
756 OriginList *ArgList = getOriginsList(*Arg);
757 assert(ArgList && "GSL pointer argument should have an origin list");
758 // GSL pointer is constructed from another gsl pointer.
759 // Example:
760 // View(View v);
761 // View(const View &v);
762 ArgList = getRValueOrigins(Arg, ArgList);
763 flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
764 } else if (Arg->getType()->isPointerType()) {
765 // GSL pointer is constructed from a raw pointer. Flow only the outermost
766 // raw pointer. Example:
767 // View(const char*);
768 // Span<int*>(const in**);
769 OriginList *ArgList = getOriginsList(*Arg);
770 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
771 getOriginsList(*CCE)->getOuterOriginID(), ArgList->getOuterOriginID(),
772 /*Kill=*/true));
773 } else {
774 // This could be a new borrow.
775 // TODO: Add code example here.
776 handleFunctionCall(CCE, CCE->getConstructor(),
777 {CCE->getArgs(), CCE->getNumArgs()},
778 /*IsGslConstruction=*/true);
779 }
780}
781
782void FactsGenerator::handleMovedArgsInCall(const FunctionDecl *FD,
783 ArrayRef<const Expr *> Args) {
784 unsigned IsInstance = 0;
785 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
786 MD && MD->isInstance() && !isa<CXXConstructorDecl>(FD)) {
787 IsInstance = 1;
788 // std::unique_ptr::release() transfers ownership.
789 // Treat it as a move to prevent false-positive warnings when the unique_ptr
790 // destructor runs after ownership has been transferred.
791 if (isUniquePtrRelease(*MD)) {
792 const Expr *UniquePtrExpr = Args[0];
793 OriginList *MovedOrigins = getOriginsList(*UniquePtrExpr);
794 if (MovedOrigins)
795 CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>(
796 UniquePtrExpr, MovedOrigins->getOuterOriginID()));
797 }
798 }
799
800 // Skip 'this' arg as it cannot be moved.
801 for (unsigned I = IsInstance;
802 I < Args.size() && I < FD->getNumParams() + IsInstance; ++I) {
803 const ParmVarDecl *PVD = FD->getParamDecl(I - IsInstance);
804 if (!PVD->getType()->isRValueReferenceType())
805 continue;
806 const Expr *Arg = Args[I];
807 OriginList *MovedOrigins = getOriginsList(*Arg);
808 assert(MovedOrigins->getLength() >= 1 &&
809 "unexpected length for r-value reference param");
810 // Arg is being moved to this parameter. Mark the origin as moved.
811 CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>(
812 Arg, MovedOrigins->getOuterOriginID()));
813 }
814}
815
816void FactsGenerator::handleInvalidatingCall(const Expr *Call,
817 const FunctionDecl *FD,
818 ArrayRef<const Expr *> Args) {
819 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
820 if (!MD || !MD->isInstance())
821 return;
822
823 if (!isInvalidationMethod(*MD))
824 return;
825
826 // Heuristics to turn-down false positives. Skip member field expressions for
827 // now. This is not a perfect filter and will still surface some false
828 // positives (e.g. `auto& r = s.v`).
829 if (!isa<DeclRefExpr>(Args[0]->IgnoreImpCasts()))
830 return;
831
832 OriginList *ThisList = getOriginsList(*Args[0]);
833 if (ThisList)
834 CurrentBlockFacts.push_back(FactMgr.createFact<InvalidateOriginFact>(
835 ThisList->getOuterOriginID(), Call));
836}
837
838void FactsGenerator::handleDestructiveCall(const Expr *Call,
839 const FunctionDecl *FD,
840 ArrayRef<const Expr *> Args) {
841 if (!destructsFirstArg(*FD))
842 return;
843 OriginList *ArgList = getOriginsList(*Args[0]);
844 if (ArgList)
845 CurrentBlockFacts.push_back(FactMgr.createFact<InvalidateOriginFact>(
846 ArgList->getOuterOriginID(), Call));
847}
848
849void FactsGenerator::handleImplicitObjectFieldUses(const Expr *Call,
850 const FunctionDecl *FD) {
851 const auto *MemberCall = dyn_cast_or_null<CXXMemberCallExpr>(Call);
852 if (!MemberCall)
853 return;
854
855 if (!isa_and_present<CXXThisExpr>(
856 MemberCall->getImplicitObjectArgument()->IgnoreImpCasts()))
857 return;
858
859 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
860 assert(MD && "Function must be a CXXMethodDecl for member calls");
861
862 const auto *ClassDecl = MD->getParent()->getDefinition();
863 if (!ClassDecl)
864 return;
865
866 const auto UseFields = [&](const CXXRecordDecl *RD) {
867 for (const auto *Field : RD->fields())
868 if (auto *FieldList = getOriginsList(*Field))
869 CurrentBlockFacts.push_back(
870 FactMgr.createFact<UseFact>(Call, FieldList));
871 };
872
873 UseFields(ClassDecl);
874
875 ClassDecl->forallBases([&](const CXXRecordDecl *Base) {
876 UseFields(Base);
877 return true;
878 });
879}
880
881void FactsGenerator::handleFunctionCall(const Expr *Call,
882 const FunctionDecl *FD,
883 ArrayRef<const Expr *> Args,
884 bool IsGslConstruction) {
885 OriginList *CallList = getOriginsList(*Call);
886 // Ignore functions returning values with no origin.
888 if (!FD)
889 return;
890 // All arguments to a function are a use of the corresponding expressions.
891 for (const Expr *Arg : Args)
892 handleUse(Arg);
893 handleInvalidatingCall(Call, FD, Args);
894 handleDestructiveCall(Call, FD, Args);
895 handleMovedArgsInCall(FD, Args);
896 handleImplicitObjectFieldUses(Call, FD);
897 if (!CallList)
898 return;
899 if (isStdReferenceCast(FD)) {
900 assert(Args.size() == 1 &&
901 "std reference cast builtins take exactly one argument");
902 // std reference-cast functions like std::move return a result that refers
903 // to the same object as the argument, so propagate the full origins.
904 flow(CallList, getOriginsList(*Args[0]), /*Kill=*/true);
905 return;
906 }
907 auto IsArgLifetimeBound = [FD, &Args](unsigned I) -> bool {
908 const ParmVarDecl *PVD = nullptr;
909 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD);
910 Method && Method->isInstance() && !isa<CXXConstructorDecl>(FD)) {
911 if (I == 0)
912 // For the 'this' argument, the attribute is on the method itself.
915 *Args[0], Method, /*RunningUnderLifetimeSafety=*/true);
916 if ((I - 1) < Method->getNumParams())
917 // For explicit arguments, find the corresponding parameter
918 // declaration.
919 PVD = Method->getParamDecl(I - 1);
920 } else if (I == 0 && shouldTrackFirstArgument(FD)) {
921 return true;
922 } else if (I == 1 && shouldTrackSecondArgument(FD)) {
923 return true;
924 } else if (I < FD->getNumParams()) {
925 // For free functions or static methods.
926 PVD = FD->getParamDecl(I);
927 }
928 return PVD ? PVD->hasAttr<clang::LifetimeBoundAttr>() : false;
929 };
930 auto shouldTrackPointerImplicitObjectArg = [FD, &Args](unsigned I) -> bool {
931 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
932 if (!Method || !Method->isInstance())
933 return false;
934 return I == 0 &&
935 isGslPointerType(Method->getFunctionObjectParameterType()) &&
937 /*RunningUnderLifetimeSafety=*/true);
938 };
939 if (Args.empty())
940 return;
941 bool KillSrc = true;
942 for (unsigned I = 0; I < Args.size(); ++I) {
943 OriginList *ArgList = getOriginsList(*Args[I]);
944 if (!ArgList)
945 continue;
946 if (IsGslConstruction) {
947 // TODO: document with code example.
948 // std::string_view(const std::string_view& from)
949 if (isGslPointerType(Args[I]->getType())) {
950 assert(!Args[I]->isGLValue() || ArgList->getLength() >= 2);
951 ArgList = getRValueOrigins(Args[I], ArgList);
952 }
953 if (isGslOwnerType(Args[I]->getType())) {
954 // The constructed gsl::Pointer borrows from the Owner's storage, not
955 // from what the Owner itself borrows, so only the outermost origin is
956 // needed.
957 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
958 CallList->getOuterOriginID(), ArgList->getOuterOriginID(),
959 KillSrc));
960 KillSrc = false;
961 } else if (IsArgLifetimeBound(I)) {
962 // Only flow the outer origin here. For lifetimebound args in
963 // gsl::Pointer construction, we do not have enough information to
964 // safely match inner origins, so the source and
965 // destination origin lists may have different lengths.
966 // FIXME: Handle origin-shape mismatches gracefully so we can also flow
967 // inner origins.
968 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
969 CallList->getOuterOriginID(), ArgList->getOuterOriginID(),
970 KillSrc));
971 KillSrc = false;
972 }
973 } else if (shouldTrackPointerImplicitObjectArg(I)) {
974 assert(ArgList->getLength() >= 2 &&
975 "Object arg of pointer type should have at least two origins");
976 // See through the GSLPointer reference to see the pointer's value.
977 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
978 CallList->getOuterOriginID(),
979 ArgList->peelOuterOrigin()->getOuterOriginID(), KillSrc));
980 KillSrc = false;
981 } else if (IsArgLifetimeBound(I)) {
982 // Lifetimebound on a non-GSL-ctor function means the returned
983 // pointer/reference itself must not outlive the arguments. This
984 // only constrains the top-level origin.
985 CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
986 CallList->getOuterOriginID(), ArgList->getOuterOriginID(), KillSrc));
987 KillSrc = false;
988 }
989 }
990}
991
992/// Checks if the expression is a `void("__lifetime_test_point_...")` cast.
993/// If so, creates a `TestPointFact` and returns true.
994bool FactsGenerator::handleTestPoint(const CXXFunctionalCastExpr *FCE) {
995 if (!FCE->getType()->isVoidType())
996 return false;
997
998 const auto *SubExpr = FCE->getSubExpr()->IgnoreParenImpCasts();
999 if (const auto *SL = dyn_cast<StringLiteral>(SubExpr)) {
1000 llvm::StringRef LiteralValue = SL->getString();
1001 const std::string Prefix = "__lifetime_test_point_";
1002
1003 if (LiteralValue.starts_with(Prefix)) {
1004 StringRef Annotation = LiteralValue.drop_front(Prefix.length());
1005 CurrentBlockFacts.push_back(
1006 FactMgr.createFact<TestPointFact>(Annotation));
1007 return true;
1008 }
1009 }
1010 return false;
1011}
1012
1013void FactsGenerator::handleUse(const Expr *E) {
1014 OriginList *List = getOriginsList(*E);
1015 if (!List)
1016 return;
1017 // For DeclRefExpr: Remove the outer layer of origin which borrows from the
1018 // decl directly (e.g., when this is not a reference). This is a use of the
1019 // underlying decl.
1020 if (auto *DRE = dyn_cast<DeclRefExpr>(E);
1021 DRE && !DRE->getDecl()->getType()->isReferenceType())
1022 List = getRValueOrigins(DRE, List);
1023 // Skip if there is no inner origin (e.g., when it is not a pointer type).
1024 if (!List)
1025 return;
1026 if (!UseFacts.contains(E)) {
1027 UseFact *UF = FactMgr.createFact<UseFact>(E, List);
1028 CurrentBlockFacts.push_back(UF);
1029 UseFacts[E] = UF;
1030 }
1031}
1032
1033void FactsGenerator::markUseAsWrite(const DeclRefExpr *DRE) {
1034 if (UseFacts.contains(DRE))
1035 UseFacts[DRE]->markAsWritten();
1036}
1037
1038// Creates an IssueFact for a new placeholder loan for each pointer or reference
1039// parameter at the function's entry.
1040llvm::SmallVector<Fact *> FactsGenerator::issuePlaceholderLoans() {
1041 const auto *FD = dyn_cast<FunctionDecl>(AC.getDecl());
1042 if (!FD)
1043 return {};
1044
1045 llvm::SmallVector<Fact *> PlaceholderLoanFacts;
1046 if (auto ThisOrigins = FactMgr.getOriginMgr().getThisOrigins()) {
1047 OriginList *List = *ThisOrigins;
1048 const Loan *L = FactMgr.getLoanMgr().createLoan(
1050 /*IssuingExpr=*/nullptr);
1051 PlaceholderLoanFacts.push_back(
1052 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
1053 }
1054 for (const ParmVarDecl *PVD : FD->parameters()) {
1055 OriginList *List = getOriginsList(*PVD);
1056 if (!List)
1057 continue;
1058 const Loan *L = FactMgr.getLoanMgr().createLoan(
1059 AccessPath::Placeholder(PVD), /*IssuingExpr=*/nullptr);
1060 PlaceholderLoanFacts.push_back(
1061 FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
1062 }
1063 return PlaceholderLoanFacts;
1064}
1065
1066} // 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:3067
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:1112
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:748
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:729
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:1641
decl_range decls()
Definition Stmt.h:1689
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:3097
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3182
Represents a function declaration or definition.
Definition Decl.h:2018
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:5335
const Expr * getInit(unsigned Init) const
Definition Expr.h:5357
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:3390
A (possibly-)qualified type.
Definition TypeBase.h:937
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3170
Expr * getRetValue()
Definition Stmt.h:3197
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 isPointerType() const
Definition TypeBase.h:8682
bool isReferenceType() const
Definition TypeBase.h:8706
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:8686
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 shouldTrackFirstArgument(const FunctionDecl *FD)
bool shouldTrackImplicitObjectArg(const Expr &ImplicitObjectArgument, const CXXMethodDecl *Callee, bool RunningUnderLifetimeSafety)
bool isUniquePtrRelease(const CXXMethodDecl &MD)
bool isStdReferenceCast(const FunctionDecl *FD)
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