clang 24.0.0git
ExprEngineCXX.cpp
Go to the documentation of this file.
1//===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- 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// This file defines the C++ expression evaluation engine.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/ParentMap.h"
17#include "clang/AST/StmtCXX.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Sequence.h"
27#include "llvm/Support/Casting.h"
28#include <optional>
29
30using namespace clang;
31using namespace ento;
32
34 ExplodedNode *Pred,
35 ExplodedNodeSet &Dst) {
36 const Expr *tempExpr = ME->getSubExpr()->IgnoreParens();
37 ProgramStateRef state = Pred->getState();
38 const StackFrame *SF = Pred->getStackFrame();
39
40 state = createTemporaryRegionIfNeeded(state, SF, tempExpr, ME);
41 Dst.insert(Engine.makePostStmtNode(ME, state, Pred));
42}
43
44void ExprEngine::performTrivialCopy(ExplodedNodeSet &Dst, ExplodedNode *Pred,
45 const CallEvent &Call) {
46 SVal ThisVal;
47 bool AlwaysReturnsLValue;
48 [[maybe_unused]] const CXXRecordDecl *ThisRD = nullptr;
49 if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) {
50 assert(Ctor->getDecl()->isTrivial());
51 assert(Ctor->getDecl()->isCopyOrMoveConstructor());
52 ThisVal = Ctor->getCXXThisVal();
53 ThisRD = Ctor->getDecl()->getParent();
54 AlwaysReturnsLValue = false;
55 } else {
56 assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
57 assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
58 OO_Equal);
59 ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
60 ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
61 AlwaysReturnsLValue = true;
62 }
63
64 const StackFrame *SF = Pred->getStackFrame();
65 const Expr *CallExpr = Call.getOriginExpr();
66
67 ExplodedNodeSet DstEval;
68
69 assert(ThisRD);
70
71 if (!ThisRD->isEmpty()) {
72 SVal V = Call.getArgSVal(0);
73 const Expr *VExpr = Call.getArgExpr(0);
74
75 // If the value being copied is not unknown, load from its location to get
76 // an aggregate rvalue.
77 if (std::optional<Loc> L = V.getAs<Loc>())
78 V = Pred->getState()->getSVal(*L);
79 else
80 assert(V.isUnknownOrUndef());
81
83 evalLocation(Tmp, CallExpr, VExpr, Pred, Pred->getState(), V,
84 /*isLoad=*/true);
85 for (ExplodedNode *N : Tmp)
86 evalBind(DstEval, CallExpr, N, ThisVal, V, !AlwaysReturnsLValue);
87 } else {
88 // We can't copy empty classes because of empty base class optimization.
89 // In that case, copying the empty base class subobject would overwrite the
90 // object that it overlaps with - so let's not do that.
91 // See issue-157467.cpp for an example.
92 DstEval.insert(Pred);
93 }
94
95 for (ExplodedNode *N : DstEval) {
96 ProgramStateRef State = N->getState();
97 if (AlwaysReturnsLValue)
98 State = State->BindExpr(CallExpr, SF, ThisVal);
99 else
100 State = bindReturnValue(Call, SF, State);
101 Dst.insert(Engine.makePostStmtNode(CallExpr, State, N));
102 }
103}
104
105SVal ExprEngine::makeElementRegion(ProgramStateRef State, SVal LValue,
106 QualType &Ty, bool &IsArray, unsigned Idx) {
107 SValBuilder &SVB = State->getStateManager().getSValBuilder();
108 ASTContext &Ctx = SVB.getContext();
109
110 if (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
111 while (AT) {
112 Ty = AT->getElementType();
113 AT = dyn_cast<ArrayType>(AT->getElementType());
114 }
115 LValue = State->getLValue(Ty, SVB.makeArrayIndex(Idx), LValue);
116 IsArray = true;
117 }
118
119 return LValue;
120}
121
122// In case when the prvalue is returned from the function (kind is one of
123// SimpleReturnedValueKind, CXX17ElidedCopyReturnedValueKind), then
124// it's materialization happens in context of the caller.
126 const Expr *E, ProgramStateRef State, unsigned NumVisitedCaller,
127 const StackFrame *SF, const ConstructionContext *CC,
128 EvalCallOptions &CallOpts, unsigned Idx) {
129
131 MemRegionManager &MRMgr = SVB.getRegionManager();
132 ASTContext &ACtx = SVB.getContext();
133
134 // Compute the target region by exploring the construction context.
135 if (CC) {
136 switch (CC->getKind()) {
139 const auto *DSCC = cast<VariableConstructionContext>(CC);
140 const auto *DS = DSCC->getDeclStmt();
141 const auto *Var = cast<VarDecl>(DS->getSingleDecl());
142 QualType Ty = Var->getType();
143 return makeElementRegion(State, State->getLValue(Var, SF), Ty,
144 CallOpts.IsArrayCtorOrDtor, Idx);
145 }
149 const auto *Init = ICC->getCXXCtorInitializer();
150 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(SF->getDecl());
151 Loc ThisPtr = SVB.getCXXThis(CurCtor, SF);
152 SVal ThisVal = State->getSVal(ThisPtr);
153 if (Init->isBaseInitializer()) {
154 const auto *ThisReg = cast<SubRegion>(ThisVal.getAsRegion());
155 const CXXRecordDecl *BaseClass =
156 Init->getBaseClass()->getAsCXXRecordDecl();
157 const auto *BaseReg =
158 MRMgr.getCXXBaseObjectRegion(BaseClass, ThisReg,
159 Init->isBaseVirtual());
160 return SVB.makeLoc(BaseReg);
161 }
162 if (Init->isDelegatingInitializer())
163 return ThisVal;
164
165 const ValueDecl *Field;
166 SVal FieldVal;
167 if (Init->isIndirectMemberInitializer()) {
168 Field = Init->getIndirectMember();
169 FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
170 } else {
171 Field = Init->getMember();
172 FieldVal = State->getLValue(Init->getMember(), ThisVal);
173 }
174
175 QualType Ty = Field->getType();
176 return makeElementRegion(State, FieldVal, Ty, CallOpts.IsArrayCtorOrDtor,
177 Idx);
178 }
180 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
181 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
182 const auto *NE = NECC->getCXXNewExpr();
183 SVal V = *getObjectUnderConstruction(State, NE, SF);
184 if (const SubRegion *MR =
185 dyn_cast_or_null<SubRegion>(V.getAsRegion())) {
186 if (NE->isArray()) {
187 CallOpts.IsArrayCtorOrDtor = true;
188
189 auto Ty = NE->getType()->getPointeeType();
190 while (const auto *AT = getContext().getAsArrayType(Ty))
191 Ty = AT->getElementType();
192
193 auto R = MRMgr.getElementRegion(Ty, svalBuilder.makeArrayIndex(Idx),
194 MR, SVB.getContext());
195
196 return loc::MemRegionVal(R);
197 }
198 return V;
199 }
200 // TODO: Detect when the allocator returns a null pointer.
201 // Constructor shall not be called in this case.
202 }
203 break;
204 }
207 // The temporary is to be managed by the parent stack frame.
208 // So build it in the parent stack frame if we're not in the
209 // top frame of the analysis.
210 if (const StackFrame *CallerSF = SF->getParent()) {
211 auto RTC = (*SF->getCallSiteBlock())[SF->getIndex()]
212 .getAs<CFGCXXRecordTypedCall>();
213 if (!RTC) {
214 // We were unable to find the correct construction context for the
215 // call in the parent stack frame. This is equivalent to not being
216 // able to find construction context at all.
217 break;
218 }
219
220 unsigned NVCaller = getNumVisited(CallerSF, SF->getCallSiteBlock());
222 SF->getCallSite(), State, NVCaller, CallerSF,
223 RTC->getConstructionContext(), CallOpts);
224 } else {
225 // We are on the top frame of the analysis. We do not know where is the
226 // object returned to. Conjure a symbolic region for the return value.
227 // TODO: We probably need a new MemRegion kind to represent the storage
228 // of that SymbolicRegion, so that we could produce a fancy symbol
229 // instead of an anonymous conjured symbol.
230 // TODO: Do we need to track the region to avoid having it dead
231 // too early? It does die too early, at least in C++17, but because
232 // putting anything into a SymbolicRegion causes an immediate escape,
233 // it doesn't cause any leak false positives.
234 const auto *RCC = cast<ReturnedValueConstructionContext>(CC);
235 // Make sure that this doesn't coincide with any other symbol
236 // conjured for the returned expression.
237 static const int TopLevelSymRegionTag = 0;
238 const Expr *RetE = RCC->getReturnStmt()->getRetValue();
239 assert(RetE && "Void returns should not have a construction context");
240 QualType ReturnTy = RetE->getType();
241 QualType RegionTy = ACtx.getPointerType(ReturnTy);
242 return SVB.conjureSymbolVal(&TopLevelSymRegionTag, getCFGElementRef(),
243 SF, RegionTy, getNumVisitedCurrent());
244 }
245 llvm_unreachable("Unhandled return value construction context!");
246 }
248 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
250
251 // Support pre-C++17 copy elision. We'll have the elidable copy
252 // constructor in the AST and in the CFG, but we'll skip it
253 // and construct directly into the final object. This call
254 // also sets the CallOpts flags for us.
255 // If the elided copy/move constructor is not supported, there's still
256 // benefit in trying to model the non-elided constructor.
257 // Stash the call options before trying to elide, as they'll get
258 // overwritten.
259 EvalCallOptions PreElideCallOpts = CallOpts;
260
262 TCC->getConstructorAfterElision(), State, NumVisitedCaller, SF,
263 TCC->getConstructionContextAfterElision(), CallOpts);
264
265 // FIXME: This definition of "copy elision has not failed" is unreliable.
266 // It doesn't indicate that the constructor will actually be inlined
267 // later; this is still up to evalCall() to decide.
269 return V;
270
271 // Copy elision failed. Revert the changes and proceed as if we have
272 // a simple temporary.
273 CallOpts = PreElideCallOpts;
275 [[fallthrough]];
276 }
278 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
279 const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
280
281 CallOpts.IsTemporaryCtorOrDtor = true;
282 if (MTE) {
283 if (const ValueDecl *VD = MTE->getExtendingDecl()) {
285 assert(SD != SD_FullExpression);
286 if (!VD->getType()->isReferenceType()) {
287 // We're lifetime-extended by a surrounding aggregate.
288 // Automatic destructors aren't quite working in this case
289 // on the CFG side. We should warn the caller about that.
290 // FIXME: Is there a better way to retrieve this information from
291 // the MaterializeTemporaryExpr?
293 }
294
295 if (SD == SD_Static || SD == SD_Thread)
296 return loc::MemRegionVal(
297 MRMgr.getCXXStaticLifetimeExtendedObjectRegion(E, VD));
298
299 return loc::MemRegionVal(
300 MRMgr.getCXXLifetimeExtendedObjectRegion(E, VD, SF));
301 }
302 assert(MTE->getStorageDuration() == SD_FullExpression);
303 }
304
305 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, SF));
306 }
308 CallOpts.IsTemporaryCtorOrDtor = true;
309
310 const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
311
313 MRMgr.getCXXTempObjectRegion(LCC->getInitializer(), SF));
314
315 const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E);
316 if (getIndexOfElementToConstruct(State, CE, SF)) {
317 CallOpts.IsArrayCtorOrDtor = true;
318 Base = State->getLValue(E->getType(), svalBuilder.makeArrayIndex(Idx),
319 Base);
320 }
321
322 return Base;
323 }
325 // Arguments are technically temporaries.
326 CallOpts.IsTemporaryCtorOrDtor = true;
327
328 const auto *ACC = cast<ArgumentConstructionContext>(CC);
329 const Expr *E = ACC->getCallLikeExpr();
330 unsigned Idx = ACC->getIndex();
331
333 auto getArgLoc = [&](CallEventRef<> Caller) -> std::optional<SVal> {
334 const StackFrame *FutureSF =
335 Caller->getCalleeStackFrame(NumVisitedCaller);
336 // Return early if we are unable to reliably foresee
337 // the future stack frame.
338 if (!FutureSF)
339 return std::nullopt;
340
341 // This should be equivalent to Caller->getDecl() for now, but
342 // FutureSF->getDecl() is likely to support better stuff (like
343 // virtual functions) earlier.
344 const Decl *CalleeD = FutureSF->getDecl();
345
346 // FIXME: Support for variadic arguments is not implemented here yet.
347 if (CallEvent::isVariadic(CalleeD))
348 return std::nullopt;
349
350 // Operator arguments do not correspond to operator parameters
351 // because this-argument is implemented as a normal argument in
352 // operator call expressions but not in operator declarations.
353 const TypedValueRegion *TVR = Caller->getParameterLocation(
354 *Caller->getAdjustedParameterIndex(Idx), NumVisitedCaller);
355 if (!TVR)
356 return std::nullopt;
357
358 return loc::MemRegionVal(TVR);
359 };
360
361 if (const auto *CE = dyn_cast<CallExpr>(E)) {
362 CallEventRef<> Caller =
363 CEMgr.getSimpleCall(CE, State, SF, getCFGElementRef());
364 if (std::optional<SVal> V = getArgLoc(Caller))
365 return *V;
366 else
367 break;
368 } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
369 // Don't bother figuring out the target region for the future
370 // constructor because we won't need it.
372 CCE, /*Target=*/nullptr, State, SF, getCFGElementRef());
373 if (std::optional<SVal> V = getArgLoc(Caller))
374 return *V;
375 else
376 break;
377 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) {
378 CallEventRef<> Caller =
379 CEMgr.getObjCMethodCall(ME, State, SF, getCFGElementRef());
380 if (std::optional<SVal> V = getArgLoc(Caller))
381 return *V;
382 else
383 break;
384 }
385 }
386 } // switch (CC->getKind())
387 }
388
389 // If we couldn't find an existing region to construct into, assume we're
390 // constructing a temporary. Notify the caller of our failure.
392 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, SF));
393}
394
396 SVal V, const Expr *E, ProgramStateRef State, const StackFrame *SF,
397 const ConstructionContext *CC, const EvalCallOptions &CallOpts) {
399 // Sounds like we failed to find the target region and therefore
400 // copy elision failed. There's nothing we can do about it here.
401 return State;
402 }
403
404 // See if we're constructing an existing region by looking at the
405 // current construction context.
406 assert(CC && "Computed target region without construction context?");
407 switch (CC->getKind()) {
410 const auto *DSCC = cast<VariableConstructionContext>(CC);
411 return addObjectUnderConstruction(State, DSCC->getDeclStmt(), SF, V);
412 }
416 const auto *Init = ICC->getCXXCtorInitializer();
417 // Base and delegating initializers handled above
418 assert(Init->isAnyMemberInitializer() &&
419 "Base and delegating initializers should have been handled by"
420 "computeObjectUnderConstruction()");
421 return addObjectUnderConstruction(State, Init, SF, V);
422 }
424 return State;
425 }
428 const StackFrame *CallerSF = SF->getParent();
429 if (!CallerSF) {
430 // No extra work is necessary in top frame.
431 return State;
432 }
433
434 auto RTC = (*SF->getCallSiteBlock())[SF->getIndex()]
435 .getAs<CFGCXXRecordTypedCall>();
436 assert(RTC && "Could not have had a target region without it");
437
439 V, SF->getCallSite(), State, CallerSF, RTC->getConstructionContext(),
440 CallOpts);
441 }
443 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
447 V, TCC->getConstructorAfterElision(), State, SF,
448 TCC->getConstructionContextAfterElision(), CallOpts);
449
450 // Remember that we've elided the constructor.
451 State = addObjectUnderConstruction(
452 State, TCC->getConstructorAfterElision(), SF, V);
453
454 // Remember that we've elided the destructor.
455 if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
456 State = elideDestructor(State, BTE, SF);
457
458 // Instead of materialization, shamelessly return
459 // the final object destination.
460 if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
461 State = addObjectUnderConstruction(State, MTE, SF, V);
462
463 return State;
464 }
465 // If we decided not to elide the constructor, proceed as if
466 // it's a simple temporary.
467 [[fallthrough]];
468 }
470 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
471 if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
472 State = addObjectUnderConstruction(State, BTE, SF, V);
473
474 if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
475 State = addObjectUnderConstruction(State, MTE, SF, V);
476
477 return State;
478 }
480 const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
481
482 // If we capture and array, we want to store the super region, not a
483 // sub-region.
484 if (const auto *EL = dyn_cast_or_null<ElementRegion>(V.getAsRegion()))
485 V = loc::MemRegionVal(EL->getSuperRegion());
486
487 return addObjectUnderConstruction(
488 State, {LCC->getLambdaExpr(), LCC->getIndex()}, SF, V);
489 }
491 const auto *ACC = cast<ArgumentConstructionContext>(CC);
492 if (const auto *BTE = ACC->getCXXBindTemporaryExpr())
493 State = addObjectUnderConstruction(State, BTE, SF, V);
494
495 return addObjectUnderConstruction(
496 State, {ACC->getCallLikeExpr(), ACC->getIndex()}, SF, V);
497 }
498 }
499 llvm_unreachable("Unhandled construction context!");
500}
501
502static ProgramStateRef
504 const ArrayInitLoopExpr *AILE,
505 const StackFrame *SF, NonLoc Idx) {
507 MemRegionManager &MRMgr = SVB.getRegionManager();
508 ASTContext &Ctx = SVB.getContext();
509
510 // HACK: There is no way we can put the index of the array element into the
511 // CFG unless we unroll the loop, so we manually select and bind the required
512 // parameter to the environment.
513 const Expr *SourceArray = AILE->getCommonExpr()->getSourceExpr();
514 const auto *Ctor =
516
517 const auto *SourceArrayRegion =
518 cast<SubRegion>(State->getSVal(SourceArray, SF).getAsRegion());
520 MRMgr.getElementRegion(Ctor->getType(), Idx, SourceArrayRegion, Ctx);
521
522 return State->BindExpr(Ctor->getArg(0), SF, loc::MemRegionVal(ElementRegion));
523}
524
525void ExprEngine::handleConstructor(const Expr *E, ExplodedNode *Pred,
526 ExplodedNodeSet &Dst) {
527 const auto *CE = dyn_cast<CXXConstructExpr>(E);
528 const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(E);
529 assert(CE || CIE);
530
531 const StackFrame *SF = Pred->getStackFrame();
532 ProgramStateRef State = Pred->getState();
533
534 SVal Target = UnknownVal();
535
536 if (CE) {
537 if (std::optional<SVal> ElidedTarget =
538 getObjectUnderConstruction(State, CE, SF)) {
539 // We've previously modeled an elidable constructor by pretending that
540 // it in fact constructs into the correct target. This constructor can
541 // therefore be skipped.
542 Target = *ElidedTarget;
543 State = finishObjectConstruction(State, CE, SF);
544 if (auto L = Target.getAs<Loc>())
545 State = State->BindExpr(CE, SF, State->getSVal(*L, CE->getType()));
546 Dst.insert(Engine.makePostStmtNode(CE, State, Pred));
547 return;
548 }
549 }
550
551 EvalCallOptions CallOpts;
552 auto C = getCurrentCFGElement().getAs<CFGConstructor>();
553 assert(C || getCurrentCFGElement().getAs<CFGStmt>());
554 const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr;
555
556 const CXXConstructionKind CK =
557 CE ? CE->getConstructionKind() : CIE->getConstructionKind();
558 switch (CK) {
560 // Inherited constructors are always base class constructors.
561 assert(CE && !CIE && "A complete constructor is inherited?!");
562
563 // If the ctor is part of an ArrayInitLoopExpr, we want to handle it
564 // differently.
565 auto *AILE = CC ? CC->getArrayInitLoop() : nullptr;
566
567 unsigned Idx = 0;
568 if (CE->getType()->isArrayType() || AILE) {
569
570 auto isZeroSizeArray = [&] {
571 uint64_t Size = 1;
572
573 if (const auto *CAT = dyn_cast<ConstantArrayType>(CE->getType()))
575 else if (AILE)
577
578 return Size == 0;
579 };
580
581 // No element construction will happen in a 0 size array.
582 if (isZeroSizeArray()) {
583 static SimpleProgramPointTag T{"ExprEngine",
584 "Skipping 0 size array construction"};
585 PostStmt Loc(CE, Pred->getStackFrame(), &T);
586 Dst.insert(Engine.makeNode(Loc, State, Pred));
587 return;
588 }
589
590 Idx = getIndexOfElementToConstruct(State, CE, SF).value_or(0u);
591 State = setIndexOfElementToConstruct(State, CE, SF, Idx + 1);
592 }
593
594 if (AILE) {
595 // Only set this once even though we loop through it multiple times.
596 if (!getPendingInitLoop(State, CE, SF))
597 State = setPendingInitLoop(
598 State, CE, SF, getContext().getArrayInitLoopExprElementCount(AILE));
599
601 State, AILE, SF, svalBuilder.makeArrayIndex(Idx));
602 }
603
604 // The target region is found from construction context.
605 std::tie(State, Target) = handleConstructionContext(CE, State, currBldrCtx,
606 SF, CC, CallOpts, Idx);
607 break;
608 }
610 // Make sure we are not calling virtual base class initializers twice.
611 // Only the most-derived object should initialize virtual base classes.
612 const auto *OuterCtor =
613 dyn_cast_or_null<CXXConstructExpr>(SF->getCallSite());
614 assert(
615 (!OuterCtor ||
616 OuterCtor->getConstructionKind() == CXXConstructionKind::Complete ||
617 OuterCtor->getConstructionKind() == CXXConstructionKind::Delegating) &&
618 ("This virtual base should have already been initialized by "
619 "the most derived class!"));
620 (void)OuterCtor;
621 [[fallthrough]];
622 }
624 // In C++17, classes with non-virtual bases may be aggregates, so they would
625 // be initialized as aggregates without a constructor call, so we may have
626 // a base class constructed directly into an initializer list without
627 // having the derived-class constructor call on the previous stack frame.
628 // Initializer lists may be nested into more initializer lists that
629 // correspond to surrounding aggregate initializations.
630 // FIXME: For now this code essentially bails out. We need to find the
631 // correct target region and set it.
632 // FIXME: Instead of relying on the ParentMap, we should have the
633 // trigger-statement (InitListExpr or CXXParenListInitExpr in this case)
634 // passed down from CFG or otherwise always available during construction.
635 if (isa_and_nonnull<InitListExpr, CXXParenListInitExpr>(
636 SF->getParentMap().getParent(E))) {
637 MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
638 Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, SF));
640 break;
641 }
642 [[fallthrough]];
644 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(SF->getDecl());
645 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor, SF);
646 SVal ThisVal = State->getSVal(ThisPtr);
647
649 Target = ThisVal;
650 } else {
651 // Cast to the base type.
652 bool IsVirtual = (CK == CXXConstructionKind::VirtualBase);
653 SVal BaseVal =
654 getStoreManager().evalDerivedToBase(ThisVal, E->getType(), IsVirtual);
655 Target = BaseVal;
656 }
657 break;
658 }
659 }
660
661 if (State != Pred->getState()) {
662 static SimpleProgramPointTag T("ExprEngine",
663 "Prepare for object construction");
664 Pred = Engine.makeNode(PreStmt(E, SF, &T), State, Pred);
665 if (!Pred)
666 return;
667 }
668
669 const MemRegion *TargetRegion = Target.getAsRegion();
670 CallEventManager &CEMgr = getStateManager().getCallEventManager();
671 CallEventRef<> Call =
672 CIE ? (CallEventRef<>)CEMgr.getCXXInheritedConstructorCall(
673 CIE, TargetRegion, State, SF, getCFGElementRef())
674 : (CallEventRef<>)CEMgr.getCXXConstructorCall(CE, TargetRegion, State,
675 SF, getCFGElementRef());
676
677 ExplodedNodeSet DstPreVisit;
678 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, E, *this);
679
680 ExplodedNodeSet PreInitialized;
681 if (CE) {
682 // FIXME: Is it possible and/or useful to do this before PreStmt?
683 for (ExplodedNode *N : DstPreVisit) {
684 ProgramStateRef State = N->getState();
685 if (CE->requiresZeroInitialization()) {
686 // FIXME: Once we properly handle constructors in new-expressions, we'll
687 // need to invalidate the region before setting a default value, to make
688 // sure there aren't any lingering bindings around. This probably needs
689 // to happen regardless of whether or not the object is zero-initialized
690 // to handle random fields of a placement-initialized object picking up
691 // old bindings. We might only want to do it when we need to, though.
692 // FIXME: This isn't actually correct for arrays -- we need to zero-
693 // initialize the entire array, not just the first element -- but our
694 // handling of arrays everywhere else is weak as well, so this shouldn't
695 // actually make things worse. Placement new makes this tricky as well,
696 // since it's then possible to be initializing one part of a multi-
697 // dimensional array.
698 const CXXRecordDecl *TargetHeldRecord =
699 dyn_cast_or_null<CXXRecordDecl>(CE->getType()->getAsRecordDecl());
700
701 if (!TargetHeldRecord || !TargetHeldRecord->isEmpty())
702 State = State->bindDefaultZero(Target, SF);
703 }
704
705 PreStmt P(CE, N->getStackFrame(), /*tag=*/nullptr);
706 PreInitialized.insert(Engine.makeNode(P, State, N));
707 }
708 } else {
709 PreInitialized = DstPreVisit;
710 }
711
712 ExplodedNodeSet DstPreCall;
713 getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
714 *Call, *this);
715
716 ExplodedNodeSet DstEvaluated;
717
718 if (CE && CE->getConstructor()->isTrivial() &&
719 CE->getConstructor()->isCopyOrMoveConstructor() &&
720 !CallOpts.IsArrayCtorOrDtor) {
721 // FIXME: Handle other kinds of trivial constructors as well.
722 for (ExplodedNode *N : DstPreCall)
723 performTrivialCopy(DstEvaluated, N, *Call);
724
725 } else {
726 for (ExplodedNode *N : DstPreCall)
727 getCheckerManager().runCheckersForEvalCall(DstEvaluated, N, *Call, *this,
728 CallOpts);
729 }
730
731 // If the CFG was constructed without elements for temporary destructors
732 // and the just-called constructor created a temporary object then
733 // stop exploration if the temporary object has a noreturn constructor.
734 // This can lose coverage because the destructor, if it were present
735 // in the CFG, would be called at the end of the full expression or
736 // later (for life-time extended temporaries) -- but avoids infeasible
737 // paths when no-return temporary destructors are used for assertions.
738 ExplodedNodeSet DstEvaluatedPostProcessed;
739 const AnalysisDeclContext *ADC = SF->getAnalysisDeclContext();
741 if (llvm::isa_and_nonnull<CXXTempObjectRegion,
742 CXXLifetimeExtendedObjectRegion>(TargetRegion) &&
744 ->getParent()
745 ->isAnyDestructorNoReturn()) {
746
747 // If we've inlined the constructor, then DstEvaluated would be empty.
748 // In this case we still want a sink, which could be implemented
749 // in processCallExit. But we don't have that implemented at the moment,
750 // so if you hit this assertion, see if you can avoid inlining
751 // the respective constructor when analyzer-config cfg-temporary-dtors
752 // is set to false.
753 // Otherwise there's nothing wrong with inlining such constructor.
754 assert(!DstEvaluated.empty() &&
755 "We should not have inlined this constructor!");
756
757 for (ExplodedNode *N : DstEvaluated) {
758 Engine.makePostStmtNode(E, N->getState(), N, /*MarkAsSink=*/true);
759 }
760
761 // There is no need to run the PostCall and PostStmt checker
762 // callbacks because we just generated sinks on all nodes in th
763 // frontier.
764 return;
765 }
766 }
767
768 DstEvaluatedPostProcessed.insert(DstEvaluated);
769 ExplodedNodeSet DstPostArgumentCleanup;
770 for (ExplodedNode *I : DstEvaluatedPostProcessed)
771 finishArgumentConstruction(DstPostArgumentCleanup, I, *Call);
772
773 // If there were other constructors called for object-type arguments
774 // of this constructor, clean them up.
775 ExplodedNodeSet DstPostCall;
777 DstPostArgumentCleanup,
778 *Call, *this);
779 getCheckerManager().runCheckersForPostStmt(Dst, DstPostCall, E, *this);
780}
781
783 ExplodedNode *Pred,
784 ExplodedNodeSet &Dst) {
785 handleConstructor(CE, Pred, Dst);
786}
787
789 const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred,
790 ExplodedNodeSet &Dst) {
791 handleConstructor(CE, Pred, Dst);
792}
793
795 const MemRegion *Dest,
796 const Stmt *S,
797 bool IsBaseDtor,
798 ExplodedNode *Pred,
799 ExplodedNodeSet &Dst,
800 EvalCallOptions &CallOpts) {
801 assert(S && "A destructor without a trigger!");
802 const StackFrame *SF = Pred->getStackFrame();
803 ProgramStateRef State = Pred->getState();
804
805 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
806 assert(RecordDecl && "Only CXXRecordDecls should have destructors");
807 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
808 // FIXME: There should always be a Decl, otherwise the destructor call
809 // shouldn't have been added to the CFG in the first place.
810 if (!DtorDecl) {
811 // Skip the invalid destructor. We cannot simply return because
812 // it would interrupt the analysis instead.
813 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
814 // FIXME: PostImplicitCall with a null decl may crash elsewhere anyway.
815 PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), SF,
816 getCFGElementRef(), &T);
817 Dst.insert(Engine.makeNode(PP, Pred->getState(), Pred));
818 return;
819 }
820
821 if (!Dest) {
822 // We're trying to destroy something that is not a region. This may happen
823 // for a variety of reasons (unknown target region, concrete integer instead
824 // of target region, etc.). The current code makes an attempt to recover.
825 // FIXME: We probably don't really need to recover when we're dealing
826 // with concrete integers specifically.
828 if (const Expr *E = dyn_cast_or_null<Expr>(S)) {
829 Dest = MRMgr.getCXXTempObjectRegion(E, Pred->getStackFrame());
830 } else {
831 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
832 Engine.makeNode(Pred->getLocation().withTag(&T), Pred->getState(), Pred,
833 /*MarkAsSink=*/true);
834 return;
835 }
836 }
837
840 DtorDecl, S, Dest, IsBaseDtor, State, SF, getCFGElementRef());
841
842 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
843 Call->getSourceRange().getBegin(),
844 "Error evaluating destructor");
845
846 ExplodedNodeSet DstPreCall;
847 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
848 *Call, *this);
849
850 ExplodedNodeSet DstInvalidated;
851 for (ExplodedNode *N : DstPreCall)
852 defaultEvalCall(DstInvalidated, N, *Call, CallOpts);
853
854 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
855 *Call, *this);
856}
857
859 ExplodedNode *Pred,
860 ExplodedNodeSet &Dst) {
861 ProgramStateRef State = Pred->getState();
862 const StackFrame *SF = Pred->getStackFrame();
863 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
864 CNE->getBeginLoc(),
865 "Error evaluating New Allocator Call");
868 CEMgr.getCXXAllocatorCall(CNE, State, SF, getCFGElementRef());
869
870 ExplodedNodeSet DstPreCall;
871 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
872 *Call, *this);
873
874 ExplodedNodeSet DstPostCall;
875 for (ExplodedNode *I : DstPreCall) {
876 // Operator new calls (CXXNewExpr) are intentionally not eval-called,
877 // because it does not make sense to eval-call user-provided functions.
878 // 1) If the new operator can be inlined, then don't prevent it from
879 // inlining by having an eval-call of that operator.
880 // 2) If it can't be inlined, then the default conservative modeling
881 // is what we want anyway.
882 // So the best is to not allow eval-calling CXXNewExprs from checkers.
883 // Checkers can provide their pre/post-call callbacks if needed.
884 defaultEvalCall(DstPostCall, I, *Call);
885 }
886 // If the call is inlined, DstPostCall will be empty and we bail out now.
887
888 // Store return value of operator new() for future use, until the actual
889 // CXXNewExpr gets processed.
890 ExplodedNodeSet DstPostValue;
891 for (ExplodedNode *I : DstPostCall) {
892 // FIXME: Because CNE serves as the "call site" for the allocator (due to
893 // lack of a better expression in the AST), the conjured return value symbol
894 // is going to be of the same type (C++ object pointer type). Technically
895 // this is not correct because the operator new's prototype always says that
896 // it returns a 'void *'. So we should change the type of the symbol,
897 // and then evaluate the cast over the symbolic pointer from 'void *' to
898 // the object pointer type. But without changing the symbol's type it
899 // is breaking too much to evaluate the no-op symbolic cast over it, so we
900 // skip it for now.
901 ProgramStateRef State = I->getState();
902 SVal RetVal = State->getSVal(CNE, SF);
903 // [basic.stc.dynamic.allocation] (on the return value of an allocation
904 // function):
905 // "The order, contiguity, and initial value of storage allocated by
906 // successive calls to an allocation function are unspecified."
907 State = State->bindDefaultInitial(RetVal, UndefinedVal{}, SF);
908
909 // If this allocation function is not declared as non-throwing, failures
910 // /must/ be signalled by exceptions, and thus the return value will never
911 // be NULL. -fno-exceptions does not influence this semantics.
912 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
913 // where new can return NULL. If we end up supporting that option, we can
914 // consider adding a check for it here.
915 // C++11 [basic.stc.dynamic.allocation]p3.
916 if (const FunctionDecl *FD = CNE->getOperatorNew()) {
917 QualType Ty = FD->getType();
918 if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
919 if (!ProtoType->isNothrow())
920 State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true);
921 }
922
923 DstPostValue.insert(Engine.makePostStmtNode(
924 CNE, addObjectUnderConstruction(State, CNE, SF, RetVal), I));
925 }
926
927 ExplodedNodeSet DstPostPostCallCallback;
928 getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
929 DstPostValue, *Call, *this);
930 for (ExplodedNode *I : DstPostPostCallCallback) {
932 }
933}
934
936 ExplodedNodeSet &Dst) {
937 // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
938 // Also, we need to decide how allocators actually work -- they're not
939 // really part of the CXXNewExpr because they happen BEFORE the
940 // CXXConstructExpr subexpression. See PR12014 for some discussion.
941
942 unsigned blockCount = getNumVisitedCurrent();
943 const StackFrame *SF = Pred->getStackFrame();
944 SVal symVal = UnknownVal();
945 FunctionDecl *FD = CNE->getOperatorNew();
946
947 bool IsStandardGlobalOpNewFunction =
949
950 ProgramStateRef State = Pred->getState();
951
952 // Retrieve the stored operator new() return value.
953 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
954 symVal = *getObjectUnderConstruction(State, CNE, SF);
955 State = finishObjectConstruction(State, CNE, SF);
956 }
957
958 // We assume all standard global 'operator new' functions allocate memory in
959 // heap. We realize this is an approximation that might not correctly model
960 // a custom global allocator.
961 if (symVal.isUnknown()) {
962 if (IsStandardGlobalOpNewFunction)
963 symVal = svalBuilder.getConjuredHeapSymbolVal(getCFGElementRef(), SF,
964 CNE->getType(), blockCount);
965 else
966 symVal = svalBuilder.conjureSymbolVal(
967 /*symbolTag=*/nullptr, getCFGElementRef(), SF, blockCount);
968 }
969
972 CEMgr.getCXXAllocatorCall(CNE, State, SF, getCFGElementRef());
973
974 if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
975 // Invalidate placement args.
976 // FIXME: Once we figure out how we want allocators to work,
977 // we should be using the usual pre-/(default-)eval-/post-call checkers
978 // here.
979 State = Call->invalidateRegions(blockCount, State);
980 if (!State)
981 return;
982
983 // If this allocation function is not declared as non-throwing, failures
984 // /must/ be signalled by exceptions, and thus the return value will never
985 // be NULL. -fno-exceptions does not influence this semantics.
986 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
987 // where new can return NULL. If we end up supporting that option, we can
988 // consider adding a check for it here.
989 // C++11 [basic.stc.dynamic.allocation]p3.
990 if (const auto *ProtoType = FD->getType()->getAs<FunctionProtoType>())
991 if (!ProtoType->isNothrow())
992 if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
993 State = State->assume(*dSymVal, true);
994 }
995
996 SVal Result = symVal;
997
998 if (CNE->isArray()) {
999
1000 if (const auto *NewReg = cast_or_null<SubRegion>(symVal.getAsRegion())) {
1001 // If each element is initialized by their default constructor, the field
1002 // values are properly placed inside the required region, however if an
1003 // initializer list is used, this doesn't happen automatically.
1004 auto *Init = CNE->getInitializer();
1005 bool isInitList =
1006 isa_and_nonnull<InitListExpr, CXXParenListInitExpr>(Init);
1007
1008 QualType ObjTy =
1009 isInitList ? Init->getType() : CNE->getType()->getPointeeType();
1010 const ElementRegion *EleReg =
1011 MRMgr.getElementRegion(ObjTy, svalBuilder.makeArrayIndex(0), NewReg,
1012 svalBuilder.getContext());
1013 Result = loc::MemRegionVal(EleReg);
1014
1015 // If the array is list initialized, we bind the initializer list to the
1016 // memory region here, otherwise we would lose it.
1017 if (isInitList) {
1018 Pred = Engine.makePostStmtNode(CNE, State, Pred);
1019
1020 SVal V = State->getSVal(Init, SF);
1022 evalBind(Evaluated, CNE, Pred, Result, V, true);
1023
1024 for (ExplodedNode *N : Evaluated)
1025 Dst.insert(Engine.makeNodeWithBinding(N, CNE, Result));
1026 return;
1027 }
1028 }
1029
1030 Dst.insert(Engine.makeNodeWithBinding(Pred, CNE, Result, State));
1031 return;
1032 }
1033
1034 // FIXME: Once we have proper support for CXXConstructExprs inside
1035 // CXXNewExpr, we need to make sure that the constructed object is not
1036 // immediately invalidated here. (The placement call should happen before
1037 // the constructor call anyway.)
1039 // Non-array placement new should always return the placement location.
1040 SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), SF);
1041 Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
1042 CNE->getPlacementArg(0)->getType());
1043 }
1044
1045 // Bind the address of the object, then check to see if we cached out.
1046 ExplodedNode *NewN = Engine.makeNodeWithBinding(Pred, CNE, Result, State);
1047 Dst.insert(NewN);
1048 if (!NewN)
1049 return;
1050
1051 // If the type is not a record, we won't have a CXXConstructExpr as an
1052 // initializer. Copy the value over.
1053 if (const Expr *Init = CNE->getInitializer()) {
1055 assert(Dst.size() == 1);
1056 Dst.erase(NewN);
1057 evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, SF),
1058 /*FirstInit=*/IsStandardGlobalOpNewFunction);
1059 }
1060 }
1061}
1062
1064 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1065
1068 CDE, Pred->getState(), Pred->getStackFrame(), getCFGElementRef());
1069
1070 ExplodedNodeSet DstPreCall;
1071 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, *Call, *this);
1072 ExplodedNodeSet DstPostCall;
1073
1074 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
1075 for (ExplodedNode *I : DstPreCall) {
1076 // Intentionally either inline or conservative eval-call the operator
1077 // delete, but avoid triggering an eval-call event for checkers.
1078 // As detailed at handling CXXNewExprs, in short, because it does not
1079 // really make sense to eval-call user-provided functions.
1080 defaultEvalCall(DstPostCall, I, *Call);
1081 }
1082 } else {
1083 DstPostCall = std::move(DstPreCall);
1084 }
1085 getCheckerManager().runCheckersForPostCall(Dst, DstPostCall, *Call, *this);
1086}
1087
1089 ExplodedNodeSet &Dst) {
1090 const VarDecl *VD = CS->getExceptionDecl();
1091 if (!VD) {
1092 Dst.insert(Pred);
1093 return;
1094 }
1095
1096 const StackFrame *SF = Pred->getStackFrame();
1097 SVal V = svalBuilder.conjureSymbolVal(getCFGElementRef(), SF, VD->getType(),
1099 ProgramStateRef state = Pred->getState();
1100 state = state->bindLoc(state->getLValue(VD, SF), V, SF);
1101
1102 Dst.insert(Engine.makePostStmtNode(CS, state, Pred));
1103}
1104
1106 ExplodedNodeSet &Dst) {
1107 // Get the this object region from StoreManager.
1108 const StackFrame *SF = Pred->getStackFrame();
1109 const MemRegion *R = svalBuilder.getRegionManager().getCXXThisRegion(
1110 getContext().getCanonicalType(TE->getType()), SF);
1111
1112 ProgramStateRef state = Pred->getState();
1113 SVal V = state->getSVal(loc::MemRegionVal(R));
1114 Dst.insert(Engine.makeNodeWithBinding(Pred, TE, V));
1115}
1116
1118 ExplodedNodeSet &Dst) {
1119 const StackFrame *SF = Pred->getStackFrame();
1120
1121 // Get the region of the lambda itself.
1122 const MemRegion *R =
1123 svalBuilder.getRegionManager().getCXXTempObjectRegion(LE, SF);
1125
1126 ProgramStateRef State = Pred->getState();
1127
1128 // If we created a new MemRegion for the lambda, we should explicitly bind
1129 // the captures.
1130 for (auto const [Idx, FieldForCapture, InitExpr] :
1131 llvm::zip(llvm::seq<unsigned>(0, -1), LE->getLambdaClass()->fields(),
1132 LE->capture_inits())) {
1133 SVal FieldLoc = State->getLValue(FieldForCapture, V);
1134
1135 SVal InitVal;
1136 if (!FieldForCapture->hasCapturedVLAType()) {
1137 assert(InitExpr && "Capture missing initialization expression");
1138
1139 // Capturing a 0 length array is a no-op, so we ignore it to get a more
1140 // accurate analysis. If it's not ignored, it would set the default
1141 // binding of the lambda to 'Unknown', which can lead to falsely detecting
1142 // 'Uninitialized' values as 'Unknown' and not reporting a warning.
1143 const auto FTy = FieldForCapture->getType();
1144 if (FTy->isConstantArrayType() &&
1145 getContext().getConstantArrayElementCount(
1146 getContext().getAsConstantArrayType(FTy)) == 0)
1147 continue;
1148
1149 // With C++17 copy elision the InitExpr can be anything, so instead of
1150 // pattern matching all cases, we simple check if the current field is
1151 // under construction or not, regardless what it's InitExpr is.
1152 if (const auto OUC = getObjectUnderConstruction(State, {LE, Idx}, SF)) {
1153 InitVal = State->getSVal(OUC->getAsRegion());
1154
1155 State = finishObjectConstruction(State, {LE, Idx}, SF);
1156 } else
1157 InitVal = State->getSVal(InitExpr, SF);
1158
1159 } else {
1160
1161 assert(!getObjectUnderConstruction(State, {LE, Idx}, SF) &&
1162 "VLA capture by value is a compile time error!");
1163
1164 // The field stores the length of a captured variable-length array.
1165 // These captures don't have initialization expressions; instead we
1166 // get the length from the VLAType size expression.
1167 Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
1168 InitVal = State->getSVal(SizeExpr, SF);
1169 }
1170
1171 State = State->bindLoc(FieldLoc, InitVal, SF);
1172 }
1173
1174 // Decay the Loc into an RValue, because there might be a
1175 // MaterializeTemporaryExpr node above this one which expects the bound value
1176 // to be an RValue.
1177 SVal LambdaRVal = State->getSVal(R);
1178
1179 // FIXME: is this the right program point kind?
1180 ExplodedNode *N = Engine.makeNodeWithBinding(Pred, LE, LambdaRVal, State,
1182
1183 // FIXME: Move all post/pre visits to ::Visit().
1184 getCheckerManager().runCheckersForPostStmt(Dst, N, LE, *this);
1185}
1186
1188 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1189 const StackFrame *SF = Pred->getStackFrame();
1190 ExplodedNodeSet CheckerPreStmt;
1191 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
1192
1193 ExplodedNodeSet EvalSet;
1194
1195 for (ExplodedNode *N : CheckerPreStmt) {
1196 ProgramStateRef State = N->getState();
1197 for (const auto *Attr : getSpecificAttrs<CXXAssumeAttr>(A->getAttrs())) {
1198 SVal AssumedVal = State->getSVal(Attr->getAssumption(), SF);
1199 // This code ignores assumptions that evaluate to UndefinedVal.
1200 // Perhaps there should be a checker that reports this situation.
1201 if (auto ValidAssumedVal = AssumedVal.getAs<DefinedOrUnknownSVal>()) {
1202 State = State->assume(*ValidAssumedVal, true);
1203 }
1204
1205 if (!State)
1206 break;
1207 }
1208
1209 if (State)
1210 EvalSet.insert(Engine.makePostStmtNode(A, State, N));
1211 }
1212
1213 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
1214}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static ProgramStateRef bindRequiredArrayElementToEnvironment(ProgramStateRef State, const ArrayInitLoopExpr *AILE, const StackFrame *SF, NonLoc Idx)
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
CFG::BuildOptions & getCFGBuildOptions()
Represents a loop initializing the elements of an array.
Definition Expr.h:5994
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6009
Attr - This represents one attribute.
Definition Attr.h:46
Represents an attribute applied to a statement.
Definition Stmt.h:2215
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2247
Represents a function call that returns a C++ object by value.
Definition CFG.h:190
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:113
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
VarDecl * getExceptionDecl() const
Definition StmtCXX.h:50
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1755
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
bool isArray() const
Definition ExprCXX.h:2468
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
SourceLocation getBeginLoc() const
Definition ExprCXX.h:2610
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
Represents the this expression in C++.
Definition ExprCXX.h:1158
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2963
ConstructionContext's subclasses describe different ways of constructing an object in C++.
virtual const ArrayInitLoopExpr * getArrayInitLoop() const
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:113
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
QualType getType() const
Definition Expr.h:145
Represents a function declaration or definition.
Definition Decl.h:2058
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions:
Definition Decl.h:2722
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition Decl.cpp:3446
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
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:4971
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4996
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4988
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5021
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1248
Stmt * getParent(Stmt *) const
Represents a program point just after an implicit call event.
If a crash happens while one of these objects are live, the message is printed out along with the spe...
ProgramPoint withTag(const ProgramPointTag *tag) const
Create a new ProgramPoint object that is the same as the original except for using the specified tag ...
A (possibly-)qualified type.
Definition TypeBase.h:938
Represents a struct/union/class.
Definition Decl.h:4459
It represents a stack frame of the call stack.
const ParentMap & getParentMap() const
unsigned getIndex() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const Expr * getCallSite() const
const Decl * getDecl() const
const StackFrame * getParent() const
It might return null.
const CFGBlock * getCallSiteBlock() const
Stmt - This represents one statement.
Definition Stmt.h:85
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
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9338
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
Represents a call to a C++ constructor.
Definition CallEvent.h:990
Manages the lifetime of CallEvent objects.
Definition CallEvent.h:1363
CallEventRef< CXXConstructorCall > getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1440
CallEventRef< CXXAllocatorCall > getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1464
CallEventRef< CXXInheritedConstructorCall > getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E, const MemRegion *Target, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1447
CallEventRef< CXXDeallocatorCall > getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1471
CallEventRef< CXXDestructorCall > getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, const MemRegion *Target, bool IsBase, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1455
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1433
CallEventRef getSimpleCall(const CallExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:152
static bool isVariadic(const Decl *D)
Returns true if the given decl is known to be variadic.
void runCheckersForPreCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng)
Run checkers for pre-visiting function calls (including methods, constructors, destructors etc.
void runCheckersForEvalCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &CE, ExprEngine &Eng, const EvalCallOptions &CallOpts)
Run checkers for evaluating a call.
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
void runCheckersForNewAllocator(const CXXAllocatorCall &Call, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, bool wasInlined=false)
Run checkers between C++ operator new and constructor calls.
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
void runCheckersForPostCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting function calls (including methods, constructors, destructors etc.
ElementRegion is used to represent both array elements and casts.
Definition MemRegion.h:1237
ExplodedNodeSet is a set of ExplodedNode * elements with the invariant that its elements cannot be nu...
void insert(ExplodedNode *N)
bool erase(ExplodedNode *N)
const ProgramStateRef & getState() const
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
const StackFrame * getStackFrame() const
ProgramStateManager & getStateManager()
Definition ExprEngine.h:477
void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst, EvalCallOptions &Options)
void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLambdaExpr - Transfer function logic for LambdaExprs.
CFGElement getCurrentCFGElement()
Return the CFG element corresponding to the worklist element that is currently being processed by Exp...
Definition ExprEngine.h:768
static std::optional< unsigned > getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E, const StackFrame *SF)
Retrieves which element is being constructed in a non-POD type array.
ProgramStateRef bindReturnValue(const CallEvent &Call, const StackFrame *SF, ProgramStateRef State)
Create a new state in which the call return value is binded to the call origin expression.
static std::optional< unsigned > getPendingInitLoop(ProgramStateRef State, const CXXConstructExpr *E, const StackFrame *SF)
Retrieves the size of the array in the pending ArrayInitLoopExpr.
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition ExprEngine.h:214
StoreManager & getStoreManager()
Definition ExprEngine.h:480
void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Create a C++ temporary object for an rvalue.
ProgramStateRef updateObjectsUnderConstruction(SVal V, const Expr *E, ProgramStateRef State, const StackFrame *SF, const ConstructionContext *CC, const EvalCallOptions &CallOpts)
Update the program state with all the path-sensitive information that's necessary to perform construc...
void defaultEvalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, const CallEvent &Call, const EvalCallOptions &CallOpts={})
Default implementation of call evaluation.
ConstCFGElementRef getCFGElementRef() const
Definition ExprEngine.h:290
CheckerManager & getCheckerManager() const
Definition ExprEngine.h:223
static std::optional< SVal > getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const StackFrame *SF)
By looking at a certain item that may be potentially part of an object's ConstructionContext,...
SVal computeObjectUnderConstruction(const Expr *E, ProgramStateRef State, unsigned NumVisitedCaller, const StackFrame *SF, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
Find location of the object that is being constructed by a given constructor.
void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
unsigned getNumVisitedCurrent() const
Definition ExprEngine.h:299
void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
std::pair< ProgramStateRef, SVal > handleConstructionContext(const Expr *E, ProgramStateRef State, const NodeBuilderContext *BldrCtx, const StackFrame *SF, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
A convenient wrapper around computeObjectUnderConstruction and updateObjectsUnderConstruction.
Definition ExprEngine.h:817
SValBuilder & getSValBuilder()
Definition ExprEngine.h:227
void VisitAttributedStmt(const AttributedStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitAttributedStmt - Transfer function logic for AttributedStmt.
unsigned getNumVisited(const StackFrame *SF, const CFGBlock *Block) const
Definition ExprEngine.h:294
const ElementRegion * getElementRegion(QualType elementType, NonLoc Idx, const SubRegion *superRegion, const ASTContext &Ctx)
getElementRegion - Retrieve the memory region associated with the associated element type,...
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
CallEventManager & getCallEventManager()
MemRegionManager & getRegionManager()
ProgramStateManager & getStateManager()
NonLoc makeArrayIndex(uint64_t idx)
ASTContext & getContext()
loc::MemRegionVal makeLoc(SymbolRef sym)
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrame *SF)
Return a memory region for the 'this' object reference.
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, ConstCFGElementRef elem, const StackFrame *SF, unsigned count)
Create a new symbol with a unique 'name'.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:88
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:84
bool isUnknown() const
Definition SVals.h:111
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition Store.cpp:254
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:480
TypedValueRegion - An abstract class representing regions having a typed value.
Definition MemRegion.h:569
Definition ARM.cpp:1102
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CXXConstructionKind
Definition ExprCXX.h:1544
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition Specifiers.h:338
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:341
@ SD_Static
Static storage duration.
Definition Specifiers.h:342
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:339
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
auto getSpecificAttrs(const Container &container)
U cast(CodeGen::Address addr)
Definition Address.h:327
Expr * extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE)
Definition CFG.cpp:1461
unsigned long uint64_t
Hints for figuring out if a call should be inlined during evalCall().
Definition ExprEngine.h:93
bool IsTemporaryLifetimeExtendedViaAggregate
This call is a constructor for a temporary that is lifetime-extended by binding it to a reference-typ...
Definition ExprEngine.h:108
bool IsTemporaryCtorOrDtor
This call is a constructor or a destructor of a temporary value.
Definition ExprEngine.h:103
bool IsArrayCtorOrDtor
This call is a constructor or a destructor for a single element within an array, a part of array cons...
Definition ExprEngine.h:100
bool IsElidableCtorThatHasNotBeenElided
This call is a pre-C++17 elidable constructor that we failed to elide because we failed to compute th...
Definition ExprEngine.h:115
bool IsCtorOrDtorWithImproperlyModeledTargetRegion
This call is a constructor or a destructor for which we do not currently compute the this-region corr...
Definition ExprEngine.h:96