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