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