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/ASTContext.h"
14#include "clang/AST/AttrIterator.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/ParentMap.h"
17#include "clang/AST/StmtCXX.h"
18#include "clang/Analysis/ConstructionContext.h"
19#include "clang/Basic/PrettyStackTrace.h"
20#include "clang/StaticAnalyzer/Core/CheckerManager.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
24#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Sequence.h"
27#include "llvm/Support/Casting.h"
28#include <optional>
29
30using namespace clang;
31using namespace ento;
32
33void ExprEngine::VisitMaterializeTemporaryExpr(
34 const MaterializeTemporaryExpr *MTE, ExplodedNode *Pred,
35 ExplodedNodeSet &Dst) {
36 const Expr *TempExpr = MTE->getSubExpr()->IgnoreParens();
37 ProgramStateRef State = Pred->getState();
38 const StackFrame *SF = Pred->getStackFrame();
39
40 State = createTemporaryRegionIfNeeded(State, SF, InitWithAdjustments: TempExpr, Result: MTE);
41 Dst.insert(N: Engine.makePostStmtNode(S: MTE, State, Pred));
42}
43
44void ExprEngine::performTrivialCopy(ExplodedNodeSet &Dst, ExplodedNode *Pred,
45 const CallEvent &Call) {
46 SVal ThisVal;
47 bool AlwaysReturnsLValue;
48 [[maybe_unused]] const CXXRecordDecl *ThisRD = nullptr;
49 if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(Val: &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>(Val: Call).getCXXThisVal();
60 ThisRD = cast<CXXMethodDecl>(Val: Call.getDecl())->getParent();
61 AlwaysReturnsLValue = true;
62 }
63
64 const StackFrame *SF = Pred->getStackFrame();
65 const Expr *CallExpr = Call.getOriginExpr();
66
67 ExplodedNodeSet DstEval;
68
69 assert(ThisRD);
70
71 if (!ThisRD->isEmpty()) {
72 SVal V = Call.getArgSVal(Index: 0);
73 const Expr *VExpr = Call.getArgExpr(Index: 0);
74
75 // If the value being copied is not unknown, load from its location to get
76 // an aggregate rvalue.
77 if (std::optional<Loc> L = V.getAs<Loc>())
78 V = Pred->getState()->getSVal(LV: *L);
79 else
80 assert(V.isUnknownOrUndef());
81
82 ExplodedNodeSet Tmp;
83 evalLocation(Dst&: Tmp, NodeEx: CallExpr, BoundEx: VExpr, Pred, St: Pred->getState(), location: V,
84 /*isLoad=*/true);
85 for (ExplodedNode *N : Tmp)
86 evalBind(Dst&: DstEval, StoreE: CallExpr, Pred: N, location: ThisVal, Val: V, AtDeclInit: !AlwaysReturnsLValue);
87 } else {
88 // We can't copy empty classes because of empty base class optimization.
89 // In that case, copying the empty base class subobject would overwrite the
90 // object that it overlaps with - so let's not do that.
91 // See issue-157467.cpp for an example.
92 DstEval.insert(N: Pred);
93 }
94
95 for (ExplodedNode *N : DstEval) {
96 ProgramStateRef State = N->getState();
97 if (AlwaysReturnsLValue)
98 State = State->BindExpr(E: CallExpr, SF, V: ThisVal);
99 else
100 State = bindReturnValue(Call, SF, State);
101 Dst.insert(N: Engine.makePostStmtNode(S: CallExpr, State, Pred: N));
102 }
103}
104
105SVal ExprEngine::makeElementRegion(ProgramStateRef State, SVal LValue,
106 QualType &Ty, bool &IsArray, unsigned Idx) {
107 SValBuilder &SVB = State->getStateManager().getSValBuilder();
108
109 if (Ty->isArrayType()) {
110 Ty = SVB.getContext().getBaseElementType(QT: Ty);
111 LValue = State->getLValue(ElementType: Ty, Idx: SVB.makeArrayIndex(idx: Idx), Base: LValue);
112 IsArray = true;
113 }
114
115 return LValue;
116}
117
118// In case when the prvalue is returned from the function (kind is one of
119// SimpleReturnedValueKind, CXX17ElidedCopyReturnedValueKind), then
120// it's materialization happens in context of the caller.
121SVal ExprEngine::computeObjectUnderConstruction(
122 const Expr *E, ProgramStateRef State, unsigned NumVisitedCaller,
123 const StackFrame *SF, const ConstructionContext *CC,
124 EvalCallOptions &CallOpts, unsigned Idx) {
125
126 SValBuilder &SVB = getSValBuilder();
127 MemRegionManager &MRMgr = SVB.getRegionManager();
128 ASTContext &ACtx = SVB.getContext();
129
130 // Compute the target region by exploring the construction context.
131 if (CC) {
132 switch (CC->getKind()) {
133 case ConstructionContext::CXX17ElidedCopyVariableKind:
134 case ConstructionContext::SimpleVariableKind: {
135 const auto *DSCC = cast<VariableConstructionContext>(Val: CC);
136 const auto *DS = DSCC->getDeclStmt();
137 const auto *Var = cast<VarDecl>(Val: DS->getSingleDecl());
138 QualType Ty = Var->getType();
139 return makeElementRegion(State, LValue: State->getLValue(VD: Var, SF), Ty,
140 IsArray&: CallOpts.IsArrayCtorOrDtor, Idx);
141 }
142 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
143 case ConstructionContext::SimpleConstructorInitializerKind: {
144 const auto *ICC = cast<ConstructorInitializerConstructionContext>(Val: CC);
145 const auto *Init = ICC->getCXXCtorInitializer();
146 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(Val: SF->getDecl());
147 Loc ThisPtr = SVB.getCXXThis(D: CurCtor, SF);
148 SVal ThisVal = State->getSVal(LV: ThisPtr);
149 if (Init->isBaseInitializer()) {
150 const auto *ThisReg = cast<SubRegion>(Val: ThisVal.getAsRegion());
151 const CXXRecordDecl *BaseClass =
152 Init->getBaseClass()->getAsCXXRecordDecl();
153 const auto *BaseReg =
154 MRMgr.getCXXBaseObjectRegion(BaseClass, Super: ThisReg,
155 IsVirtual: Init->isBaseVirtual());
156 return SVB.makeLoc(region: BaseReg);
157 }
158 if (Init->isDelegatingInitializer())
159 return ThisVal;
160
161 const ValueDecl *Field;
162 SVal FieldVal;
163 if (Init->isIndirectMemberInitializer()) {
164 Field = Init->getIndirectMember();
165 FieldVal = State->getLValue(decl: Init->getIndirectMember(), Base: ThisVal);
166 } else {
167 Field = Init->getMember();
168 FieldVal = State->getLValue(decl: Init->getMember(), Base: ThisVal);
169 }
170
171 QualType Ty = Field->getType();
172 return makeElementRegion(State, LValue: FieldVal, Ty, IsArray&: CallOpts.IsArrayCtorOrDtor,
173 Idx);
174 }
175 case ConstructionContext::NewAllocatedObjectKind: {
176 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
177 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(Val: CC);
178 const auto *NE = NECC->getCXXNewExpr();
179 SVal V = *getObjectUnderConstruction(State, Item: NE, SF);
180 if (const SubRegion *MR =
181 dyn_cast_or_null<SubRegion>(Val: V.getAsRegion())) {
182 if (NE->isArray()) {
183 CallOpts.IsArrayCtorOrDtor = true;
184
185 auto Ty = NE->getType()->getPointeeType();
186 while (const auto *AT = getContext().getAsArrayType(T: Ty))
187 Ty = AT->getElementType();
188
189 auto R = MRMgr.getElementRegion(elementType: Ty, Idx: svalBuilder.makeArrayIndex(idx: Idx),
190 superRegion: MR, Ctx: SVB.getContext());
191
192 return loc::MemRegionVal(R);
193 }
194 return V;
195 }
196 // TODO: Detect when the allocator returns a null pointer.
197 // Constructor shall not be called in this case.
198 }
199 break;
200 }
201 case ConstructionContext::SimpleReturnedValueKind:
202 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
203 // The temporary is to be managed by the parent stack frame.
204 // So build it in the parent stack frame if we're not in the
205 // top frame of the analysis.
206 if (const StackFrame *CallerSF = SF->getParent()) {
207 auto RTC = (*SF->getCallSiteBlock())[SF->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
216 unsigned NVCaller = getNumVisited(SF: CallerSF, Block: SF->getCallSiteBlock());
217 return computeObjectUnderConstruction(
218 E: SF->getCallSite(), State, NumVisitedCaller: NVCaller, SF: CallerSF,
219 CC: 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>(Val: 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(T: ReturnTy);
238 return SVB.conjureSymbolVal(symbolTag: &TopLevelSymRegionTag, elem: getCFGElementRef(),
239 SF, type: RegionTy, count: getNumVisitedCurrent());
240 }
241 llvm_unreachable("Unhandled return value construction context!");
242 }
243 case ConstructionContext::ElidedTemporaryObjectKind: {
244 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
245 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(Val: 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 the call options before trying to elide, as they'll get
254 // overwritten.
255 EvalCallOptions PreElideCallOpts = CallOpts;
256
257 SVal V = computeObjectUnderConstruction(
258 E: TCC->getConstructorAfterElision(), State, NumVisitedCaller, SF,
259 CC: 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.
264 if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion)
265 return V;
266
267 // Copy elision failed. Revert the changes and proceed as if we have
268 // a simple temporary.
269 CallOpts = PreElideCallOpts;
270 CallOpts.IsElidableCtorThatHasNotBeenElided = true;
271 [[fallthrough]];
272 }
273 case ConstructionContext::SimpleTemporaryObjectKind: {
274 const auto *TCC = cast<TemporaryObjectConstructionContext>(Val: CC);
275 const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
276
277 CallOpts.IsTemporaryCtorOrDtor = true;
278 if (MTE) {
279 if (const ValueDecl *VD = MTE->getExtendingDecl()) {
280 StorageDuration SD = MTE->getStorageDuration();
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?
288 CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true;
289 }
290
291 if (SD == SD_Static || SD == SD_Thread)
292 return loc::MemRegionVal(
293 MRMgr.getCXXStaticLifetimeExtendedObjectRegion(Ex: E, VD));
294
295 return loc::MemRegionVal(
296 MRMgr.getCXXLifetimeExtendedObjectRegion(Ex: E, VD, SF));
297 }
298 assert(MTE->getStorageDuration() == SD_FullExpression);
299 }
300
301 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(Ex: E, SF));
302 }
303 case ConstructionContext::LambdaCaptureKind: {
304 CallOpts.IsTemporaryCtorOrDtor = true;
305
306 const auto *LCC = cast<LambdaCaptureConstructionContext>(Val: CC);
307
308 SVal Base = loc::MemRegionVal(
309 MRMgr.getCXXTempObjectRegion(Ex: LCC->getInitializer(), SF));
310
311 const auto *CE = dyn_cast_or_null<CXXConstructExpr>(Val: E);
312 if (getIndexOfElementToConstruct(State, E: CE, SF)) {
313 CallOpts.IsArrayCtorOrDtor = true;
314 Base = State->getLValue(ElementType: E->getType(), Idx: svalBuilder.makeArrayIndex(idx: Idx),
315 Base);
316 }
317
318 return Base;
319 }
320 case ConstructionContext::ArgumentKind: {
321 // Arguments are technically temporaries.
322 CallOpts.IsTemporaryCtorOrDtor = true;
323
324 const auto *ACC = cast<ArgumentConstructionContext>(Val: CC);
325 const Expr *E = ACC->getCallLikeExpr();
326 unsigned Idx = ACC->getIndex();
327
328 CallEventManager &CEMgr = getStateManager().getCallEventManager();
329 auto getArgLoc = [&](CallEventRef<> Caller) -> std::optional<SVal> {
330 const StackFrame *FutureSF =
331 Caller->getCalleeStackFrame(BlockCount: NumVisitedCaller);
332 // Return early if we are unable to reliably foresee
333 // the future stack frame.
334 if (!FutureSF)
335 return std::nullopt;
336
337 // This should be equivalent to Caller->getDecl() for now, but
338 // FutureSF->getDecl() is likely to support better stuff (like
339 // virtual functions) earlier.
340 const Decl *CalleeD = FutureSF->getDecl();
341
342 // FIXME: Support for variadic arguments is not implemented here yet.
343 if (CallEvent::isVariadic(D: 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 Index: *Caller->getAdjustedParameterIndex(ASTArgumentIndex: Idx), BlockCount: NumVisitedCaller);
351 if (!TVR)
352 return std::nullopt;
353
354 return loc::MemRegionVal(TVR);
355 };
356
357 if (const auto *CE = dyn_cast<CallExpr>(Val: E)) {
358 CallEventRef<> Caller =
359 CEMgr.getSimpleCall(E: CE, State, SF, ElemRef: 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>(Val: E)) {
365 // Don't bother figuring out the target region for the future
366 // constructor because we won't need it.
367 CallEventRef<> Caller = CEMgr.getCXXConstructorCall(
368 E: CCE, /*Target=*/nullptr, State, SF, ElemRef: 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>(Val: E)) {
374 CallEventRef<> Caller =
375 CEMgr.getObjCMethodCall(E: ME, State, SF, ElemRef: 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.
387 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
388 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(Ex: E, SF));
389}
390
391ProgramStateRef ExprEngine::updateObjectsUnderConstruction(
392 SVal V, const Expr *E, ProgramStateRef State, const StackFrame *SF,
393 const ConstructionContext *CC, const EvalCallOptions &CallOpts) {
394 if (CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) {
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()) {
404 case ConstructionContext::CXX17ElidedCopyVariableKind:
405 case ConstructionContext::SimpleVariableKind: {
406 const auto *DSCC = cast<VariableConstructionContext>(Val: CC);
407 return addObjectUnderConstruction(State, Item: DSCC->getDeclStmt(), SF, V);
408 }
409 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
410 case ConstructionContext::SimpleConstructorInitializerKind: {
411 const auto *ICC = cast<ConstructorInitializerConstructionContext>(Val: 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, Item: Init, SF, V);
418 }
419 case ConstructionContext::NewAllocatedObjectKind: {
420 return State;
421 }
422 case ConstructionContext::SimpleReturnedValueKind:
423 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
424 const StackFrame *CallerSF = SF->getParent();
425 if (!CallerSF) {
426 // No extra work is necessary in top frame.
427 return State;
428 }
429
430 auto RTC = (*SF->getCallSiteBlock())[SF->getIndex()]
431 .getAs<CFGCXXRecordTypedCall>();
432 assert(RTC && "Could not have had a target region without it");
433
434 return updateObjectsUnderConstruction(
435 V, E: SF->getCallSite(), State, SF: CallerSF, CC: RTC->getConstructionContext(),
436 CallOpts);
437 }
438 case ConstructionContext::ElidedTemporaryObjectKind: {
439 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
440 if (!CallOpts.IsElidableCtorThatHasNotBeenElided) {
441 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(Val: CC);
442 State = updateObjectsUnderConstruction(
443 V, E: TCC->getConstructorAfterElision(), State, SF,
444 CC: TCC->getConstructionContextAfterElision(), CallOpts);
445
446 // Remember that we've elided the constructor.
447 State = addObjectUnderConstruction(
448 State, Item: TCC->getConstructorAfterElision(), SF, V);
449
450 // Remember that we've elided the destructor.
451 if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
452 State = elideDestructor(State, BTE, SF);
453
454 // Instead of materialization, shamelessly return
455 // the final object destination.
456 if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
457 State = addObjectUnderConstruction(State, Item: MTE, SF, V);
458
459 return State;
460 }
461 // If we decided not to elide the constructor, proceed as if
462 // it's a simple temporary.
463 [[fallthrough]];
464 }
465 case ConstructionContext::SimpleTemporaryObjectKind: {
466 const auto *TCC = cast<TemporaryObjectConstructionContext>(Val: CC);
467 if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
468 State = addObjectUnderConstruction(State, Item: BTE, SF, V);
469
470 if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
471 State = addObjectUnderConstruction(State, Item: MTE, SF, V);
472
473 return State;
474 }
475 case ConstructionContext::LambdaCaptureKind: {
476 const auto *LCC = cast<LambdaCaptureConstructionContext>(Val: CC);
477
478 // If we capture and array, we want to store the super region, not a
479 // sub-region.
480 if (const auto *EL = dyn_cast_or_null<ElementRegion>(Val: V.getAsRegion()))
481 V = loc::MemRegionVal(EL->getSuperRegion());
482
483 return addObjectUnderConstruction(
484 State, Item: {LCC->getLambdaExpr(), LCC->getIndex()}, SF, V);
485 }
486 case ConstructionContext::ArgumentKind: {
487 const auto *ACC = cast<ArgumentConstructionContext>(Val: CC);
488 if (const auto *BTE = ACC->getCXXBindTemporaryExpr())
489 State = addObjectUnderConstruction(State, Item: BTE, SF, V);
490
491 return addObjectUnderConstruction(
492 State, Item: {ACC->getCallLikeExpr(), ACC->getIndex()}, SF, V);
493 }
494 }
495 llvm_unreachable("Unhandled construction context!");
496}
497
498static ProgramStateRef
499bindRequiredArrayElementToEnvironment(ProgramStateRef State,
500 const ArrayInitLoopExpr *AILE,
501 const StackFrame *SF, NonLoc Idx) {
502 SValBuilder &SVB = State->getStateManager().getSValBuilder();
503 MemRegionManager &MRMgr = SVB.getRegionManager();
504 ASTContext &Ctx = SVB.getContext();
505
506 // HACK: There is no way we can put the index of the array element into the
507 // CFG unless we unroll the loop, so we manually select and bind the required
508 // parameter to the environment.
509 const Expr *SourceArray = AILE->getCommonExpr()->getSourceExpr();
510 const auto *Ctor =
511 cast<CXXConstructExpr>(Val: extractElementInitializerFromNestedAILE(AILE));
512
513 const auto *SourceArrayRegion =
514 cast<SubRegion>(Val: State->getSVal(E: SourceArray, SF).getAsRegion());
515 const ElementRegion *ElementRegion =
516 MRMgr.getElementRegion(elementType: Ctor->getType(), Idx, superRegion: SourceArrayRegion, Ctx);
517
518 return State->BindExpr(E: Ctor->getArg(Arg: 0), SF, V: loc::MemRegionVal(ElementRegion));
519}
520
521void ExprEngine::handleConstructor(const Expr *E, ExplodedNode *Pred,
522 ExplodedNodeSet &Dst) {
523 const auto *CE = dyn_cast<CXXConstructExpr>(Val: E);
524 const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(Val: E);
525 assert(CE || CIE);
526
527 const StackFrame *SF = Pred->getStackFrame();
528 ProgramStateRef State = Pred->getState();
529
530 SVal Target = UnknownVal();
531
532 if (CE) {
533 if (std::optional<SVal> ElidedTarget =
534 getObjectUnderConstruction(State, Item: CE, SF)) {
535 // We've previously modeled an elidable constructor by pretending that
536 // it in fact constructs into the correct target. This constructor can
537 // therefore be skipped.
538 Target = *ElidedTarget;
539 State = finishObjectConstruction(State, Item: CE, SF);
540 if (auto L = Target.getAs<Loc>())
541 State = State->BindExpr(E: CE, SF, V: State->getSVal(LV: *L, T: CE->getType()));
542 Dst.insert(N: Engine.makePostStmtNode(S: CE, State, Pred));
543 return;
544 }
545 }
546
547 EvalCallOptions CallOpts;
548 auto C = getCurrentCFGElement().getAs<CFGConstructor>();
549 assert(C || getCurrentCFGElement().getAs<CFGStmt>());
550 const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr;
551
552 const CXXConstructionKind CK =
553 CE ? CE->getConstructionKind() : CIE->getConstructionKind();
554 switch (CK) {
555 case CXXConstructionKind::Complete: {
556 // Inherited constructors are always base class constructors.
557 assert(CE && !CIE && "A complete constructor is inherited?!");
558
559 // If the ctor is part of an ArrayInitLoopExpr, we want to handle it
560 // differently.
561 auto *AILE = CC ? CC->getArrayInitLoop() : nullptr;
562
563 unsigned Idx = 0;
564 if (CE->getType()->isArrayType() || AILE) {
565
566 auto isZeroSizeArray = [&] {
567 uint64_t Size = 1;
568
569 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: CE->getType()))
570 Size = getContext().getConstantArrayElementCount(CA: CAT);
571 else if (AILE)
572 Size = getContext().getArrayInitLoopExprElementCount(AILE);
573
574 return Size == 0;
575 };
576
577 // No element construction will happen in a 0 size array.
578 if (isZeroSizeArray()) {
579 static SimpleProgramPointTag T{"ExprEngine",
580 "Skipping 0 size array construction"};
581 PostStmt Loc(CE, Pred->getStackFrame(), &T);
582 Dst.insert(N: Engine.makeNode(Loc, State, Pred));
583 return;
584 }
585
586 Idx = getIndexOfElementToConstruct(State, E: CE, SF).value_or(u: 0u);
587 State = setIndexOfElementToConstruct(State, E: CE, SF, Idx: Idx + 1);
588 }
589
590 if (AILE) {
591 // Only set this once even though we loop through it multiple times.
592 if (!getPendingInitLoop(State, E: CE, SF))
593 State = setPendingInitLoop(
594 State, E: CE, SF, Idx: getContext().getArrayInitLoopExprElementCount(AILE));
595
596 State = bindRequiredArrayElementToEnvironment(
597 State, AILE, SF, Idx: svalBuilder.makeArrayIndex(idx: Idx));
598 }
599
600 // The target region is found from construction context.
601 std::tie(args&: State, args&: Target) =
602 handleConstructionContext(E: CE, State, SF, CC, CallOpts, Idx);
603 break;
604 }
605 case CXXConstructionKind::VirtualBase: {
606 // Make sure we are not calling virtual base class initializers twice.
607 // Only the most-derived object should initialize virtual base classes.
608 const auto *OuterCtor =
609 dyn_cast_or_null<CXXConstructExpr>(Val: SF->getCallSite());
610 assert(
611 (!OuterCtor ||
612 OuterCtor->getConstructionKind() == CXXConstructionKind::Complete ||
613 OuterCtor->getConstructionKind() == CXXConstructionKind::Delegating) &&
614 ("This virtual base should have already been initialized by "
615 "the most derived class!"));
616 (void)OuterCtor;
617 [[fallthrough]];
618 }
619 case CXXConstructionKind::NonVirtualBase:
620 // In C++17, classes with non-virtual bases may be aggregates, so they would
621 // be initialized as aggregates without a constructor call, so we may have
622 // a base class constructed directly into an initializer list without
623 // having the derived-class constructor call on the previous stack frame.
624 // Initializer lists may be nested into more initializer lists that
625 // correspond to surrounding aggregate initializations.
626 // FIXME: For now this code essentially bails out. We need to find the
627 // correct target region and set it.
628 // FIXME: Instead of relying on the ParentMap, we should have the
629 // trigger-statement (InitListExpr or CXXParenListInitExpr in this case)
630 // passed down from CFG or otherwise always available during construction.
631 if (isa_and_nonnull<InitListExpr, CXXParenListInitExpr>(
632 Val: SF->getParentMap().getParent(S: E))) {
633 MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
634 Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(Ex: E, SF));
635 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
636 break;
637 }
638 [[fallthrough]];
639 case CXXConstructionKind::Delegating: {
640 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(Val: SF->getDecl());
641 Loc ThisPtr = getSValBuilder().getCXXThis(D: CurCtor, SF);
642 SVal ThisVal = State->getSVal(LV: ThisPtr);
643
644 if (CK == CXXConstructionKind::Delegating) {
645 Target = ThisVal;
646 } else {
647 // Cast to the base type.
648 bool IsVirtual = (CK == CXXConstructionKind::VirtualBase);
649 SVal BaseVal =
650 getStoreManager().evalDerivedToBase(Derived: ThisVal, DerivedPtrType: E->getType(), IsVirtual);
651 Target = BaseVal;
652 }
653 break;
654 }
655 }
656
657 if (State != Pred->getState()) {
658 static SimpleProgramPointTag T("ExprEngine",
659 "Prepare for object construction");
660 Pred = Engine.makeNode(Loc: PreStmt(E, SF, &T), State, Pred);
661 if (!Pred)
662 return;
663 }
664
665 const MemRegion *TargetRegion = Target.getAsRegion();
666 CallEventManager &CEMgr = getStateManager().getCallEventManager();
667 CallEventRef<> Call =
668 CIE ? (CallEventRef<>)CEMgr.getCXXInheritedConstructorCall(
669 E: CIE, Target: TargetRegion, State, SF, ElemRef: getCFGElementRef())
670 : (CallEventRef<>)CEMgr.getCXXConstructorCall(E: CE, Target: TargetRegion, State,
671 SF, ElemRef: getCFGElementRef());
672
673 ExplodedNodeSet DstPreVisit;
674 getCheckerManager().runCheckersForPreStmt(Dst&: DstPreVisit, Src: Pred, S: E, Eng&: *this);
675
676 ExplodedNodeSet PreInitialized;
677 if (CE) {
678 // FIXME: Is it possible and/or useful to do this before PreStmt?
679 for (ExplodedNode *N : DstPreVisit) {
680 ProgramStateRef State = N->getState();
681 if (CE->requiresZeroInitialization()) {
682 // FIXME: Once we properly handle constructors in new-expressions, we'll
683 // need to invalidate the region before setting a default value, to make
684 // sure there aren't any lingering bindings around. This probably needs
685 // to happen regardless of whether or not the object is zero-initialized
686 // to handle random fields of a placement-initialized object picking up
687 // old bindings. We might only want to do it when we need to, though.
688 // FIXME: This isn't actually correct for arrays -- we need to zero-
689 // initialize the entire array, not just the first element -- but our
690 // handling of arrays everywhere else is weak as well, so this shouldn't
691 // actually make things worse. Placement new makes this tricky as well,
692 // since it's then possible to be initializing one part of a multi-
693 // dimensional array.
694 const CXXRecordDecl *TargetHeldRecord =
695 dyn_cast_or_null<CXXRecordDecl>(Val: CE->getType()->getAsRecordDecl());
696
697 if (!TargetHeldRecord || !TargetHeldRecord->isEmpty())
698 State = State->bindDefaultZero(loc: Target, SF);
699 }
700
701 PreStmt P(CE, N->getStackFrame(), /*tag=*/nullptr);
702 PreInitialized.insert(N: Engine.makeNode(Loc: P, State, Pred: N));
703 }
704 } else {
705 PreInitialized = DstPreVisit;
706 }
707
708 ExplodedNodeSet DstPreCall;
709 getCheckerManager().runCheckersForPreCall(Dst&: DstPreCall, Src: PreInitialized,
710 Call: *Call, Eng&: *this);
711
712 ExplodedNodeSet DstEvaluated;
713
714 if (CE && CE->getConstructor()->isTrivial() &&
715 CE->getConstructor()->isCopyOrMoveConstructor() &&
716 !CallOpts.IsArrayCtorOrDtor) {
717 // FIXME: Handle other kinds of trivial constructors as well.
718 for (ExplodedNode *N : DstPreCall)
719 performTrivialCopy(Dst&: DstEvaluated, Pred: N, Call: *Call);
720
721 } else {
722 for (ExplodedNode *N : DstPreCall)
723 getCheckerManager().runCheckersForEvalCall(Dst&: DstEvaluated, Src: N, CE: *Call, Eng&: *this,
724 CallOpts);
725 }
726
727 // If the CFG was constructed without elements for temporary destructors
728 // and the just-called constructor created a temporary object then
729 // stop exploration if the temporary object has a noreturn constructor.
730 // This can lose coverage because the destructor, if it were present
731 // in the CFG, would be called at the end of the full expression or
732 // later (for life-time extended temporaries) -- but avoids infeasible
733 // paths when no-return temporary destructors are used for assertions.
734 ExplodedNodeSet DstEvaluatedPostProcessed;
735 const AnalysisDeclContext *ADC = SF->getAnalysisDeclContext();
736 if (!ADC->getCFGBuildOptions().AddTemporaryDtors) {
737 if (llvm::isa_and_nonnull<CXXTempObjectRegion,
738 CXXLifetimeExtendedObjectRegion>(Val: TargetRegion) &&
739 cast<CXXConstructorDecl>(Val: Call->getDecl())
740 ->getParent()
741 ->isAnyDestructorNoReturn()) {
742
743 // If we've inlined the constructor, then DstEvaluated would be empty.
744 // In this case we still want a sink, which could be implemented
745 // in processCallExit. But we don't have that implemented at the moment,
746 // so if you hit this assertion, see if you can avoid inlining
747 // the respective constructor when analyzer-config cfg-temporary-dtors
748 // is set to false.
749 // Otherwise there's nothing wrong with inlining such constructor.
750 assert(!DstEvaluated.empty() &&
751 "We should not have inlined this constructor!");
752
753 for (ExplodedNode *N : DstEvaluated) {
754 Engine.makePostStmtNode(S: E, State: N->getState(), Pred: N, /*MarkAsSink=*/true);
755 }
756
757 // There is no need to run the PostCall and PostStmt checker
758 // callbacks because we just generated sinks on all nodes in th
759 // frontier.
760 return;
761 }
762 }
763
764 DstEvaluatedPostProcessed.insert(S: DstEvaluated);
765 ExplodedNodeSet DstPostArgumentCleanup;
766 for (ExplodedNode *I : DstEvaluatedPostProcessed)
767 finishArgumentConstruction(Dst&: DstPostArgumentCleanup, Pred: I, Call: *Call);
768
769 // If there were other constructors called for object-type arguments
770 // of this constructor, clean them up.
771 ExplodedNodeSet DstPostCall;
772 getCheckerManager().runCheckersForPostCall(Dst&: DstPostCall,
773 Src: DstPostArgumentCleanup,
774 Call: *Call, Eng&: *this);
775 getCheckerManager().runCheckersForPostStmt(Dst, Src: DstPostCall, S: E, Eng&: *this);
776}
777
778void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
779 ExplodedNode *Pred,
780 ExplodedNodeSet &Dst) {
781 handleConstructor(E: CE, Pred, Dst);
782}
783
784void ExprEngine::VisitCXXInheritedCtorInitExpr(
785 const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred,
786 ExplodedNodeSet &Dst) {
787 handleConstructor(E: CE, Pred, Dst);
788}
789
790void ExprEngine::VisitCXXDestructor(QualType ObjectType,
791 const MemRegion *Dest,
792 const Stmt *S,
793 bool IsBaseDtor,
794 ExplodedNode *Pred,
795 ExplodedNodeSet &Dst,
796 EvalCallOptions &CallOpts) {
797 assert(S && "A destructor without a trigger!");
798 const StackFrame *SF = Pred->getStackFrame();
799 ProgramStateRef State = Pred->getState();
800
801 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
802 assert(RecordDecl && "Only CXXRecordDecls should have destructors");
803 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
804 // FIXME: There should always be a Decl, otherwise the destructor call
805 // shouldn't have been added to the CFG in the first place.
806 if (!DtorDecl) {
807 // Skip the invalid destructor. We cannot simply return because
808 // it would interrupt the analysis instead.
809 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
810 // FIXME: PostImplicitCall with a null decl may crash elsewhere anyway.
811 PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), SF,
812 getCFGElementRef(), &T);
813 Dst.insert(N: Engine.makeNode(Loc: PP, State: Pred->getState(), Pred));
814 return;
815 }
816
817 if (!Dest) {
818 // We're trying to destroy something that is not a region. This may happen
819 // for a variety of reasons (unknown target region, concrete integer instead
820 // of target region, etc.). The current code makes an attempt to recover.
821 // FIXME: We probably don't really need to recover when we're dealing
822 // with concrete integers specifically.
823 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
824 if (const Expr *E = dyn_cast_or_null<Expr>(Val: S)) {
825 Dest = MRMgr.getCXXTempObjectRegion(Ex: E, SF: Pred->getStackFrame());
826 } else {
827 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
828 Engine.makeNode(Loc: Pred->getLocation().withTag(tag: &T), State: Pred->getState(), Pred,
829 /*MarkAsSink=*/true);
830 return;
831 }
832 }
833
834 CallEventManager &CEMgr = getStateManager().getCallEventManager();
835 CallEventRef<CXXDestructorCall> Call = CEMgr.getCXXDestructorCall(
836 DD: DtorDecl, Trigger: S, Target: Dest, IsBase: IsBaseDtor, State, SF, ElemRef: getCFGElementRef());
837
838 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
839 Call->getSourceRange().getBegin(),
840 "Error evaluating destructor");
841
842 ExplodedNodeSet DstPreCall;
843 getCheckerManager().runCheckersForPreCall(Dst&: DstPreCall, Src: Pred,
844 Call: *Call, Eng&: *this);
845
846 ExplodedNodeSet DstInvalidated;
847 for (ExplodedNode *N : DstPreCall)
848 defaultEvalCall(Dst&: DstInvalidated, Pred: N, Call: *Call, CallOpts);
849
850 getCheckerManager().runCheckersForPostCall(Dst, Src: DstInvalidated,
851 Call: *Call, Eng&: *this);
852}
853
854void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
855 ExplodedNode *Pred,
856 ExplodedNodeSet &Dst) {
857 ProgramStateRef State = Pred->getState();
858 const StackFrame *SF = Pred->getStackFrame();
859 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
860 CNE->getBeginLoc(),
861 "Error evaluating New Allocator Call");
862 CallEventManager &CEMgr = getStateManager().getCallEventManager();
863 CallEventRef<CXXAllocatorCall> Call =
864 CEMgr.getCXXAllocatorCall(E: CNE, State, SF, ElemRef: getCFGElementRef());
865
866 ExplodedNodeSet DstPreCall;
867 getCheckerManager().runCheckersForPreCall(Dst&: DstPreCall, Src: Pred,
868 Call: *Call, Eng&: *this);
869
870 ExplodedNodeSet DstPostCall;
871 for (ExplodedNode *I : DstPreCall) {
872 // Operator new calls (CXXNewExpr) are intentionally not eval-called,
873 // because it does not make sense to eval-call user-provided functions.
874 // 1) If the new operator can be inlined, then don't prevent it from
875 // inlining by having an eval-call of that operator.
876 // 2) If it can't be inlined, then the default conservative modeling
877 // is what we want anyway.
878 // So the best is to not allow eval-calling CXXNewExprs from checkers.
879 // Checkers can provide their pre/post-call callbacks if needed.
880 defaultEvalCall(Dst&: DstPostCall, Pred: I, Call: *Call);
881 }
882 // If the call is inlined, DstPostCall will be empty and we bail out now.
883
884 // Store return value of operator new() for future use, until the actual
885 // CXXNewExpr gets processed.
886 ExplodedNodeSet DstPostValue;
887 for (ExplodedNode *I : DstPostCall) {
888 // FIXME: Because CNE serves as the "call site" for the allocator (due to
889 // lack of a better expression in the AST), the conjured return value symbol
890 // is going to be of the same type (C++ object pointer type). Technically
891 // this is not correct because the operator new's prototype always says that
892 // it returns a 'void *'. So we should change the type of the symbol,
893 // and then evaluate the cast over the symbolic pointer from 'void *' to
894 // the object pointer type. But without changing the symbol's type it
895 // is breaking too much to evaluate the no-op symbolic cast over it, so we
896 // skip it for now.
897 ProgramStateRef State = I->getState();
898 SVal RetVal = State->getSVal(E: CNE, SF);
899 // [basic.stc.dynamic.allocation] (on the return value of an allocation
900 // function):
901 // "The order, contiguity, and initial value of storage allocated by
902 // successive calls to an allocation function are unspecified."
903 State = State->bindDefaultInitial(loc: RetVal, V: UndefinedVal{}, SF);
904
905 // If this allocation function is not declared as non-throwing, failures
906 // /must/ be signalled by exceptions, and thus the return value will never
907 // be NULL. -fno-exceptions does not influence this semantics.
908 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
909 // where new can return NULL. If we end up supporting that option, we can
910 // consider adding a check for it here.
911 // C++11 [basic.stc.dynamic.allocation]p3.
912 if (const FunctionDecl *FD = CNE->getOperatorNew()) {
913 QualType Ty = FD->getType();
914 if (const auto *ProtoType = Ty->getAs<FunctionProtoType>())
915 if (!ProtoType->isNothrow())
916 State = State->assume(Cond: RetVal.castAs<DefinedOrUnknownSVal>(), Assumption: true);
917 }
918
919 DstPostValue.insert(N: Engine.makePostStmtNode(
920 S: CNE, State: addObjectUnderConstruction(State, Item: CNE, SF, V: RetVal), Pred: I));
921 }
922
923 ExplodedNodeSet DstPostPostCallCallback;
924 getCheckerManager().runCheckersForPostCall(Dst&: DstPostPostCallCallback,
925 Src: DstPostValue, Call: *Call, Eng&: *this);
926 for (ExplodedNode *I : DstPostPostCallCallback) {
927 getCheckerManager().runCheckersForNewAllocator(Call: *Call, Dst, Pred: I, Eng&: *this);
928 }
929}
930
931void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
932 ExplodedNodeSet &Dst) {
933 // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
934 // Also, we need to decide how allocators actually work -- they're not
935 // really part of the CXXNewExpr because they happen BEFORE the
936 // CXXConstructExpr subexpression. See PR12014 for some discussion.
937
938 unsigned blockCount = getNumVisitedCurrent();
939 const StackFrame *SF = Pred->getStackFrame();
940 SVal symVal = UnknownVal();
941 FunctionDecl *FD = CNE->getOperatorNew();
942
943 bool IsStandardGlobalOpNewFunction =
944 FD->isReplaceableGlobalAllocationFunction();
945
946 ProgramStateRef State = Pred->getState();
947
948 // Retrieve the stored operator new() return value.
949 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
950 symVal = *getObjectUnderConstruction(State, Item: CNE, SF);
951 State = finishObjectConstruction(State, Item: CNE, SF);
952 }
953
954 // We assume all standard global 'operator new' functions allocate memory in
955 // heap. We realize this is an approximation that might not correctly model
956 // a custom global allocator.
957 if (symVal.isUnknown()) {
958 if (IsStandardGlobalOpNewFunction)
959 symVal = svalBuilder.getConjuredHeapSymbolVal(elem: getCFGElementRef(), SF,
960 type: CNE->getType(), Count: blockCount);
961 else
962 symVal = svalBuilder.conjureSymbolVal(
963 /*symbolTag=*/nullptr, elem: getCFGElementRef(), SF, count: blockCount);
964 }
965
966 CallEventManager &CEMgr = getStateManager().getCallEventManager();
967 CallEventRef<CXXAllocatorCall> Call =
968 CEMgr.getCXXAllocatorCall(E: CNE, State, SF, ElemRef: getCFGElementRef());
969
970 if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
971 // Invalidate placement args.
972 // FIXME: Once we figure out how we want allocators to work,
973 // we should be using the usual pre-/(default-)eval-/post-call checkers
974 // here.
975 State = Call->invalidateRegions(BlockCount: blockCount, State);
976 if (!State)
977 return;
978
979 // If this allocation function is not declared as non-throwing, failures
980 // /must/ be signalled by exceptions, and thus the return value will never
981 // be NULL. -fno-exceptions does not influence this semantics.
982 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case
983 // where new can return NULL. If we end up supporting that option, we can
984 // consider adding a check for it here.
985 // C++11 [basic.stc.dynamic.allocation]p3.
986 if (const auto *ProtoType = FD->getType()->getAs<FunctionProtoType>())
987 if (!ProtoType->isNothrow())
988 if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>())
989 State = State->assume(Cond: *dSymVal, Assumption: true);
990 }
991
992 SVal Result = symVal;
993
994 if (CNE->isArray()) {
995
996 if (const auto *NewReg = cast_or_null<SubRegion>(Val: symVal.getAsRegion())) {
997 // If each element is initialized by their default constructor, the field
998 // values are properly placed inside the required region, however if an
999 // initializer list is used, this doesn't happen automatically.
1000 auto *Init = CNE->getInitializer();
1001 bool isInitList =
1002 isa_and_nonnull<InitListExpr, CXXParenListInitExpr>(Val: Init);
1003
1004 QualType ObjTy =
1005 isInitList ? Init->getType() : CNE->getType()->getPointeeType();
1006 const ElementRegion *EleReg =
1007 MRMgr.getElementRegion(elementType: ObjTy, Idx: svalBuilder.makeArrayIndex(idx: 0), superRegion: NewReg,
1008 Ctx: svalBuilder.getContext());
1009 Result = loc::MemRegionVal(EleReg);
1010
1011 // If the array is list initialized, we bind the initializer list to the
1012 // memory region here, otherwise we would lose it.
1013 if (isInitList) {
1014 Pred = Engine.makePostStmtNode(S: CNE, State, Pred);
1015
1016 SVal V = State->getSVal(E: Init, SF);
1017 ExplodedNodeSet Evaluated;
1018 evalBind(Dst&: Evaluated, StoreE: CNE, Pred, location: Result, Val: V, AtDeclInit: true);
1019
1020 for (ExplodedNode *N : Evaluated)
1021 Dst.insert(N: Engine.makeNodeWithBinding(Pred: N, E: CNE, V: Result));
1022 return;
1023 }
1024 }
1025
1026 Dst.insert(N: Engine.makeNodeWithBinding(Pred, E: CNE, V: Result, State));
1027 return;
1028 }
1029
1030 // FIXME: Once we have proper support for CXXConstructExprs inside
1031 // CXXNewExpr, we need to make sure that the constructed object is not
1032 // immediately invalidated here. (The placement call should happen before
1033 // the constructor call anyway.)
1034 if (FD->isReservedGlobalPlacementOperator()) {
1035 // Non-array placement new should always return the placement location.
1036 SVal PlacementLoc = State->getSVal(E: CNE->getPlacementArg(I: 0), SF);
1037 Result = svalBuilder.evalCast(V: PlacementLoc, CastTy: CNE->getType(),
1038 OriginalTy: CNE->getPlacementArg(I: 0)->getType());
1039 }
1040
1041 // Bind the address of the object, then check to see if we cached out.
1042 ExplodedNode *NewN = Engine.makeNodeWithBinding(Pred, E: CNE, V: Result, State);
1043 Dst.insert(N: NewN);
1044 if (!NewN)
1045 return;
1046
1047 // If the type is not a record, we won't have a CXXConstructExpr as an
1048 // initializer. Copy the value over.
1049 if (const Expr *Init = CNE->getInitializer()) {
1050 if (!isa<CXXConstructExpr>(Val: Init)) {
1051 assert(Dst.size() == 1);
1052 Dst.erase(N: NewN);
1053 evalBind(Dst, StoreE: CNE, Pred: NewN, location: Result, Val: State->getSVal(E: Init, SF),
1054 /*FirstInit=*/AtDeclInit: IsStandardGlobalOpNewFunction);
1055 }
1056 }
1057}
1058
1059void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
1060 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1061
1062 CallEventManager &CEMgr = getStateManager().getCallEventManager();
1063 CallEventRef<CXXDeallocatorCall> Call = CEMgr.getCXXDeallocatorCall(
1064 E: CDE, State: Pred->getState(), SF: Pred->getStackFrame(), ElemRef: getCFGElementRef());
1065
1066 ExplodedNodeSet DstPreCall;
1067 getCheckerManager().runCheckersForPreCall(Dst&: DstPreCall, Src: Pred, Call: *Call, Eng&: *this);
1068 ExplodedNodeSet DstPostCall;
1069
1070 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
1071 for (ExplodedNode *I : DstPreCall) {
1072 // Intentionally either inline or conservative eval-call the operator
1073 // delete, but avoid triggering an eval-call event for checkers.
1074 // As detailed at handling CXXNewExprs, in short, because it does not
1075 // really make sense to eval-call user-provided functions.
1076 defaultEvalCall(Dst&: DstPostCall, Pred: I, Call: *Call);
1077 }
1078 } else {
1079 DstPostCall = std::move(DstPreCall);
1080 }
1081 getCheckerManager().runCheckersForPostCall(Dst, Src: DstPostCall, Call: *Call, Eng&: *this);
1082}
1083
1084void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
1085 ExplodedNodeSet &Dst) {
1086 const VarDecl *VD = CS->getExceptionDecl();
1087 if (!VD) {
1088 Dst.insert(N: Pred);
1089 return;
1090 }
1091
1092 const StackFrame *SF = Pred->getStackFrame();
1093 SVal V = svalBuilder.conjureSymbolVal(elem: getCFGElementRef(), SF, type: VD->getType(),
1094 visitCount: getNumVisitedCurrent());
1095 ProgramStateRef state = Pred->getState();
1096 state = state->bindLoc(location: state->getLValue(VD, SF), V, SF);
1097
1098 Dst.insert(N: Engine.makePostStmtNode(S: CS, State: state, Pred));
1099}
1100
1101void ExprEngine::VisitCXXParenListInitExpr(const CXXParenListInitExpr *E,
1102 ExplodedNode *Pred,
1103 ExplodedNodeSet &Dst) {
1104 ConstructInitList(Source: E, Args: E->getInitExprs(), /*IsTransparent*/ false, Pred, Dst);
1105}
1106
1107void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
1108 ExplodedNodeSet &Dst) {
1109 // Get the this object region from StoreManager.
1110 const StackFrame *SF = Pred->getStackFrame();
1111 const MemRegion *R = svalBuilder.getRegionManager().getCXXThisRegion(
1112 thisPointerTy: getContext().getCanonicalType(T: TE->getType()), SF);
1113
1114 ProgramStateRef state = Pred->getState();
1115 SVal V = state->getSVal(LV: loc::MemRegionVal(R));
1116 Dst.insert(N: Engine.makeNodeWithBinding(Pred, E: TE, V));
1117}
1118
1119void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
1120 ExplodedNodeSet &Dst) {
1121
1122 if (!AMgr.options.ShouldInlineLambdas) {
1123 const ExplodedNode *Node = Engine.makePostStmtNode(
1124 S: LE, State: Pred->getState(), Pred, /*MarkAsSink=*/true);
1125 Engine.addAbortedBlock(node: Node, block: getCurrBlock());
1126 return;
1127 }
1128
1129 const StackFrame *SF = Pred->getStackFrame();
1130
1131 // Get the region of the lambda itself.
1132 const MemRegion *R =
1133 svalBuilder.getRegionManager().getCXXTempObjectRegion(Ex: LE, SF);
1134 SVal V = loc::MemRegionVal(R);
1135
1136 ProgramStateRef State = Pred->getState();
1137
1138 // If we created a new MemRegion for the lambda, we should explicitly bind
1139 // the captures.
1140 for (auto const [Idx, FieldForCapture, InitExpr] :
1141 llvm::zip(t: llvm::seq<unsigned>(Begin: 0, End: -1), u: LE->getLambdaClass()->fields(),
1142 args: LE->capture_inits())) {
1143 SVal FieldLoc = State->getLValue(decl: FieldForCapture, Base: V);
1144
1145 SVal InitVal;
1146 if (!FieldForCapture->hasCapturedVLAType()) {
1147 assert(InitExpr && "Capture missing initialization expression");
1148
1149 // Capturing a 0 length array is a no-op, so we ignore it to get a more
1150 // accurate analysis. If it's not ignored, it would set the default
1151 // binding of the lambda to 'Unknown', which can lead to falsely detecting
1152 // 'Uninitialized' values as 'Unknown' and not reporting a warning.
1153 const auto FTy = FieldForCapture->getType();
1154 if (FTy->isConstantArrayType() &&
1155 getContext().getConstantArrayElementCount(
1156 CA: getContext().getAsConstantArrayType(T: FTy)) == 0)
1157 continue;
1158
1159 // With C++17 copy elision the InitExpr can be anything, so instead of
1160 // pattern matching all cases, we simple check if the current field is
1161 // under construction or not, regardless what it's InitExpr is.
1162 if (const auto OUC = getObjectUnderConstruction(State, Item: {LE, Idx}, SF)) {
1163 InitVal = State->getSVal(R: OUC->getAsRegion());
1164
1165 State = finishObjectConstruction(State, Item: {LE, Idx}, SF);
1166 } else
1167 InitVal = State->getSVal(E: InitExpr, SF);
1168
1169 } else {
1170
1171 assert(!getObjectUnderConstruction(State, {LE, Idx}, SF) &&
1172 "VLA capture by value is a compile time error!");
1173
1174 // The field stores the length of a captured variable-length array.
1175 // These captures don't have initialization expressions; instead we
1176 // get the length from the VLAType size expression.
1177 Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr();
1178 InitVal = State->getSVal(E: SizeExpr, SF);
1179 }
1180
1181 State = State->bindLoc(LV: FieldLoc, V: InitVal, SF);
1182 }
1183
1184 // Decay the Loc into an RValue, because there might be a
1185 // MaterializeTemporaryExpr node above this one which expects the bound value
1186 // to be an RValue.
1187 SVal LambdaRVal = State->getSVal(R);
1188
1189 // FIXME: is this the right program point kind?
1190 ExplodedNode *N = Engine.makeNodeWithBinding(Pred, E: LE, V: LambdaRVal, State,
1191 K: ProgramPoint::PostLValueKind);
1192
1193 // FIXME: Move all post/pre visits to ::Visit().
1194 getCheckerManager().runCheckersForPostStmt(Dst, Src: N, S: LE, Eng&: *this);
1195}
1196
1197void ExprEngine::VisitAttributedStmt(const AttributedStmt *A,
1198 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1199 const StackFrame *SF = Pred->getStackFrame();
1200 ProgramStateRef State = Pred->getState();
1201
1202 for (const auto *Attr : getSpecificAttrs<CXXAssumeAttr>(container: A->getAttrs())) {
1203 SVal AssumedVal = State->getSVal(E: Attr->getAssumption(), SF);
1204 // This code ignores assumptions that evaluate to UndefinedVal.
1205 // Perhaps there should be a checker that reports this situation.
1206 if (auto ValidAssumedVal = AssumedVal.getAs<DefinedOrUnknownSVal>()) {
1207 State = State->assume(Cond: *ValidAssumedVal, Assumption: true);
1208 }
1209
1210 if (!State)
1211 break;
1212 }
1213
1214 if (State)
1215 Dst.insert(N: Engine.makePostStmtNode(S: A, State, Pred));
1216}
1217