clang 24.0.0git
ExprEngineCXX.cpp
Go to the documentation of this file.
1//===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the C++ expression evaluation engine.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/ParentMap.h"
17#include "clang/AST/StmtCXX.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Sequence.h"
27#include "llvm/Support/Casting.h"
28#include <optional>
29
30using namespace clang;
31using namespace ento;
32
34 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, TempExpr, MTE);
41 Dst.insert(Engine.makePostStmtNode(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>(&Call)) {
50 assert(Ctor->getDecl()->isTrivial());
51 assert(Ctor->getDecl()->isCopyOrMoveConstructor());
52 ThisVal = Ctor->getCXXThisVal();
53 ThisRD = Ctor->getDecl()->getParent();
54 AlwaysReturnsLValue = false;
55 } else {
56 assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
57 assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
58 OO_Equal);
59 ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
60 ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
61 AlwaysReturnsLValue = true;
62 }
63
64 const StackFrame *SF = Pred->getStackFrame();
65 const Expr *CallExpr = Call.getOriginExpr();
66
67 ExplodedNodeSet DstEval;
68
69 assert(ThisRD);
70
71 if (!ThisRD->isEmpty()) {
72 SVal V = Call.getArgSVal(0);
73 const Expr *VExpr = Call.getArgExpr(0);
74
75 // If the value being copied is not unknown, load from its location to get
76 // an aggregate rvalue.
77 if (std::optional<Loc> L = V.getAs<Loc>())
78 V = Pred->getState()->getSVal(*L);
79 else
80 assert(V.isUnknownOrUndef());
81
83 evalLocation(Tmp, CallExpr, VExpr, Pred, Pred->getState(), V,
84 /*isLoad=*/true);
85 for (ExplodedNode *N : Tmp)
86 evalBind(DstEval, CallExpr, N, ThisVal, V, !AlwaysReturnsLValue);
87 } else {
88 // We can't copy empty classes because of empty base class optimization.
89 // In that case, copying the empty base class subobject would overwrite the
90 // object that it overlaps with - so let's not do that.
91 // See issue-157467.cpp for an example.
92 DstEval.insert(Pred);
93 }
94
95 for (ExplodedNode *N : DstEval) {
96 ProgramStateRef State = N->getState();
97 if (AlwaysReturnsLValue)
98 State = State->BindExpr(CallExpr, SF, ThisVal);
99 else
100 State = bindReturnValue(Call, SF, State);
101 Dst.insert(Engine.makePostStmtNode(CallExpr, State, N));
102 }
103}
104
105SVal ExprEngine::makeElementRegion(ProgramStateRef State, SVal LValue,
106 QualType &Ty, bool &IsArray, unsigned Idx) {
107 SValBuilder &SVB = State->getStateManager().getSValBuilder();
108
109 if (Ty->isArrayType()) {
110 Ty = SVB.getContext().getBaseElementType(Ty);
111 LValue = State->getLValue(Ty, SVB.makeArrayIndex(Idx), 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.
122 const Expr *E, ProgramStateRef State, unsigned NumVisitedCaller,
123 const StackFrame *SF, const ConstructionContext *CC,
124 EvalCallOptions &CallOpts, unsigned Idx) {
125
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()) {
135 const auto *DSCC = cast<VariableConstructionContext>(CC);
136 const auto *DS = DSCC->getDeclStmt();
137 const auto *Var = cast<VarDecl>(DS->getSingleDecl());
138 QualType Ty = Var->getType();
139 return makeElementRegion(State, State->getLValue(Var, SF), Ty,
140 CallOpts.IsArrayCtorOrDtor, Idx);
141 }
145 const auto *Init = ICC->getCXXCtorInitializer();
146 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(SF->getDecl());
147 Loc ThisPtr = SVB.getCXXThis(CurCtor, SF);
148 SVal ThisVal = State->getSVal(ThisPtr);
149 if (Init->isBaseInitializer()) {
150 const auto *ThisReg = cast<SubRegion>(ThisVal.getAsRegion());
151 const CXXRecordDecl *BaseClass =
152 Init->getBaseClass()->getAsCXXRecordDecl();
153 const auto *BaseReg =
154 MRMgr.getCXXBaseObjectRegion(BaseClass, ThisReg,
155 Init->isBaseVirtual());
156 return SVB.makeLoc(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(Init->getIndirectMember(), ThisVal);
166 } else {
167 Field = Init->getMember();
168 FieldVal = State->getLValue(Init->getMember(), ThisVal);
169 }
170
171 QualType Ty = Field->getType();
172 return makeElementRegion(State, FieldVal, Ty, CallOpts.IsArrayCtorOrDtor,
173 Idx);
174 }
176 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
177 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
178 const auto *NE = NECC->getCXXNewExpr();
179 SVal V = *getObjectUnderConstruction(State, NE, SF);
180 if (const SubRegion *MR =
181 dyn_cast_or_null<SubRegion>(V.getAsRegion())) {
182 if (NE->isArray()) {
183 CallOpts.IsArrayCtorOrDtor = true;
184
185 auto Ty = NE->getType()->getPointeeType();
186 while (const auto *AT = getContext().getAsArrayType(Ty))
187 Ty = AT->getElementType();
188
189 auto R = MRMgr.getElementRegion(Ty, svalBuilder.makeArrayIndex(Idx),
190 MR, 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 }
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(CallerSF, SF->getCallSiteBlock());
218 SF->getCallSite(), State, NVCaller, CallerSF,
219 RTC->getConstructionContext(), CallOpts);
220 } else {
221 // We are on the top frame of the analysis. We do not know where is the
222 // object returned to. Conjure a symbolic region for the return value.
223 // TODO: We probably need a new MemRegion kind to represent the storage
224 // of that SymbolicRegion, so that we could produce a fancy symbol
225 // instead of an anonymous conjured symbol.
226 // TODO: Do we need to track the region to avoid having it dead
227 // too early? It does die too early, at least in C++17, but because
228 // putting anything into a SymbolicRegion causes an immediate escape,
229 // it doesn't cause any leak false positives.
230 const auto *RCC = cast<ReturnedValueConstructionContext>(CC);
231 // Make sure that this doesn't coincide with any other symbol
232 // conjured for the returned expression.
233 static const int TopLevelSymRegionTag = 0;
234 const Expr *RetE = RCC->getReturnStmt()->getRetValue();
235 assert(RetE && "Void returns should not have a construction context");
236 QualType ReturnTy = RetE->getType();
237 QualType RegionTy = ACtx.getPointerType(ReturnTy);
238 return SVB.conjureSymbolVal(&TopLevelSymRegionTag, getCFGElementRef(),
239 SF, RegionTy, getNumVisitedCurrent());
240 }
241 llvm_unreachable("Unhandled return value construction context!");
242 }
244 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
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
258 TCC->getConstructorAfterElision(), State, NumVisitedCaller, SF,
259 TCC->getConstructionContextAfterElision(), CallOpts);
260
261 // FIXME: This definition of "copy elision has not failed" is unreliable.
262 // It doesn't indicate that the constructor will actually be inlined
263 // later; this is still up to evalCall() to decide.
265 return V;
266
267 // Copy elision failed. Revert the changes and proceed as if we have
268 // a simple temporary.
269 CallOpts = PreElideCallOpts;
271 [[fallthrough]];
272 }
274 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
275 const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr();
276
277 CallOpts.IsTemporaryCtorOrDtor = true;
278 if (MTE) {
279 if (const ValueDecl *VD = MTE->getExtendingDecl()) {
281 assert(SD != SD_FullExpression);
282 if (!VD->getType()->isReferenceType()) {
283 // We're lifetime-extended by a surrounding aggregate.
284 // Automatic destructors aren't quite working in this case
285 // on the CFG side. We should warn the caller about that.
286 // FIXME: Is there a better way to retrieve this information from
287 // the MaterializeTemporaryExpr?
289 }
290
291 if (SD == SD_Static || SD == SD_Thread)
292 return loc::MemRegionVal(
293 MRMgr.getCXXStaticLifetimeExtendedObjectRegion(E, VD));
294
295 return loc::MemRegionVal(
296 MRMgr.getCXXLifetimeExtendedObjectRegion(E, VD, SF));
297 }
298 assert(MTE->getStorageDuration() == SD_FullExpression);
299 }
300
301 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, SF));
302 }
304 CallOpts.IsTemporaryCtorOrDtor = true;
305
306 const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
307
309 MRMgr.getCXXTempObjectRegion(LCC->getInitializer(), SF));
310
311 const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E);
312 if (getIndexOfElementToConstruct(State, CE, SF)) {
313 CallOpts.IsArrayCtorOrDtor = true;
314 Base = State->getLValue(E->getType(), svalBuilder.makeArrayIndex(Idx),
315 Base);
316 }
317
318 return Base;
319 }
321 // Arguments are technically temporaries.
322 CallOpts.IsTemporaryCtorOrDtor = true;
323
324 const auto *ACC = cast<ArgumentConstructionContext>(CC);
325 const Expr *E = ACC->getCallLikeExpr();
326 unsigned Idx = ACC->getIndex();
327
329 auto getArgLoc = [&](CallEventRef<> Caller) -> std::optional<SVal> {
330 const StackFrame *FutureSF =
331 Caller->getCalleeStackFrame(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(CalleeD))
344 return std::nullopt;
345
346 // Operator arguments do not correspond to operator parameters
347 // because this-argument is implemented as a normal argument in
348 // operator call expressions but not in operator declarations.
349 const TypedValueRegion *TVR = Caller->getParameterLocation(
350 *Caller->getAdjustedParameterIndex(Idx), NumVisitedCaller);
351 if (!TVR)
352 return std::nullopt;
353
354 return loc::MemRegionVal(TVR);
355 };
356
357 if (const auto *CE = dyn_cast<CallExpr>(E)) {
358 CallEventRef<> Caller =
359 CEMgr.getSimpleCall(CE, State, SF, getCFGElementRef());
360 if (std::optional<SVal> V = getArgLoc(Caller))
361 return *V;
362 else
363 break;
364 } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
365 // Don't bother figuring out the target region for the future
366 // constructor because we won't need it.
368 CCE, /*Target=*/nullptr, State, SF, getCFGElementRef());
369 if (std::optional<SVal> V = getArgLoc(Caller))
370 return *V;
371 else
372 break;
373 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) {
374 CallEventRef<> Caller =
375 CEMgr.getObjCMethodCall(ME, State, SF, getCFGElementRef());
376 if (std::optional<SVal> V = getArgLoc(Caller))
377 return *V;
378 else
379 break;
380 }
381 }
382 } // switch (CC->getKind())
383 }
384
385 // If we couldn't find an existing region to construct into, assume we're
386 // constructing a temporary. Notify the caller of our failure.
388 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, SF));
389}
390
392 SVal V, const Expr *E, ProgramStateRef State, const StackFrame *SF,
393 const ConstructionContext *CC, const EvalCallOptions &CallOpts) {
395 // Sounds like we failed to find the target region and therefore
396 // copy elision failed. There's nothing we can do about it here.
397 return State;
398 }
399
400 // See if we're constructing an existing region by looking at the
401 // current construction context.
402 assert(CC && "Computed target region without construction context?");
403 switch (CC->getKind()) {
406 const auto *DSCC = cast<VariableConstructionContext>(CC);
407 return addObjectUnderConstruction(State, DSCC->getDeclStmt(), SF, V);
408 }
412 const auto *Init = ICC->getCXXCtorInitializer();
413 // Base and delegating initializers handled above
414 assert(Init->isAnyMemberInitializer() &&
415 "Base and delegating initializers should have been handled by"
416 "computeObjectUnderConstruction()");
417 return addObjectUnderConstruction(State, Init, SF, V);
418 }
420 return State;
421 }
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
435 V, SF->getCallSite(), State, CallerSF, RTC->getConstructionContext(),
436 CallOpts);
437 }
439 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors);
443 V, TCC->getConstructorAfterElision(), State, SF,
444 TCC->getConstructionContextAfterElision(), CallOpts);
445
446 // Remember that we've elided the constructor.
447 State = addObjectUnderConstruction(
448 State, 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, 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 }
466 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC);
467 if (const auto *BTE = TCC->getCXXBindTemporaryExpr())
468 State = addObjectUnderConstruction(State, BTE, SF, V);
469
470 if (const auto *MTE = TCC->getMaterializedTemporaryExpr())
471 State = addObjectUnderConstruction(State, MTE, SF, V);
472
473 return State;
474 }
476 const auto *LCC = cast<LambdaCaptureConstructionContext>(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>(V.getAsRegion()))
481 V = loc::MemRegionVal(EL->getSuperRegion());
482
483 return addObjectUnderConstruction(
484 State, {LCC->getLambdaExpr(), LCC->getIndex()}, SF, V);
485 }
487 const auto *ACC = cast<ArgumentConstructionContext>(CC);
488 if (const auto *BTE = ACC->getCXXBindTemporaryExpr())
489 State = addObjectUnderConstruction(State, BTE, SF, V);
490
491 return addObjectUnderConstruction(
492 State, {ACC->getCallLikeExpr(), ACC->getIndex()}, SF, V);
493 }
494 }
495 llvm_unreachable("Unhandled construction context!");
496}
497
498static ProgramStateRef
500 const ArrayInitLoopExpr *AILE,
501 const StackFrame *SF, NonLoc Idx) {
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 =
512
513 const auto *SourceArrayRegion =
514 cast<SubRegion>(State->getSVal(SourceArray, SF).getAsRegion());
516 MRMgr.getElementRegion(Ctor->getType(), Idx, SourceArrayRegion, Ctx);
517
518 return State->BindExpr(Ctor->getArg(0), SF, loc::MemRegionVal(ElementRegion));
519}
520
521void ExprEngine::handleConstructor(const Expr *E, ExplodedNode *Pred,
522 ExplodedNodeSet &Dst) {
523 const auto *CE = dyn_cast<CXXConstructExpr>(E);
524 const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(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, 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, CE, SF);
540 if (auto L = Target.getAs<Loc>())
541 State = State->BindExpr(CE, SF, State->getSVal(*L, CE->getType()));
542 Dst.insert(Engine.makePostStmtNode(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) {
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>(CE->getType()))
571 else if (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(Engine.makeNode(Loc, State, Pred));
583 return;
584 }
585
586 Idx = getIndexOfElementToConstruct(State, CE, SF).value_or(0u);
587 State = setIndexOfElementToConstruct(State, CE, SF, Idx + 1);
588 }
589
590 if (AILE) {
591 // Only set this once even though we loop through it multiple times.
592 if (!getPendingInitLoop(State, CE, SF))
593 State = setPendingInitLoop(
594 State, CE, SF, getContext().getArrayInitLoopExprElementCount(AILE));
595
597 State, AILE, SF, svalBuilder.makeArrayIndex(Idx));
598 }
599
600 // The target region is found from construction context.
601 std::tie(State, Target) =
602 handleConstructionContext(CE, State, SF, CC, CallOpts, Idx);
603 break;
604 }
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>(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 }
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 SF->getParentMap().getParent(E))) {
633 MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
634 Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, SF));
636 break;
637 }
638 [[fallthrough]];
640 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(SF->getDecl());
641 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor, SF);
642 SVal ThisVal = State->getSVal(ThisPtr);
643
645 Target = ThisVal;
646 } else {
647 // Cast to the base type.
648 bool IsVirtual = (CK == CXXConstructionKind::VirtualBase);
649 SVal BaseVal =
650 getStoreManager().evalDerivedToBase(ThisVal, 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(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 CIE, TargetRegion, State, SF, getCFGElementRef())
670 : (CallEventRef<>)CEMgr.getCXXConstructorCall(CE, TargetRegion, State,
671 SF, getCFGElementRef());
672
673 ExplodedNodeSet DstPreVisit;
674 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, E, *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>(CE->getType()->getAsRecordDecl());
696
697 if (!TargetHeldRecord || !TargetHeldRecord->isEmpty())
698 State = State->bindDefaultZero(Target, SF);
699 }
700
701 PreStmt P(CE, N->getStackFrame(), /*tag=*/nullptr);
702 PreInitialized.insert(Engine.makeNode(P, State, N));
703 }
704 } else {
705 PreInitialized = DstPreVisit;
706 }
707
708 ExplodedNodeSet DstPreCall;
709 getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
710 *Call, *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(DstEvaluated, N, *Call);
720
721 } else {
722 for (ExplodedNode *N : DstPreCall)
723 getCheckerManager().runCheckersForEvalCall(DstEvaluated, N, *Call, *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();
737 if (llvm::isa_and_nonnull<CXXTempObjectRegion,
738 CXXLifetimeExtendedObjectRegion>(TargetRegion) &&
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(E, N->getState(), 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(DstEvaluated);
765 ExplodedNodeSet DstPostArgumentCleanup;
766 for (ExplodedNode *I : DstEvaluatedPostProcessed)
767 finishArgumentConstruction(DstPostArgumentCleanup, I, *Call);
768
769 // If there were other constructors called for object-type arguments
770 // of this constructor, clean them up.
771 ExplodedNodeSet DstPostCall;
773 DstPostArgumentCleanup,
774 *Call, *this);
775 getCheckerManager().runCheckersForPostStmt(Dst, DstPostCall, E, *this);
776}
777
779 ExplodedNode *Pred,
780 ExplodedNodeSet &Dst) {
781 handleConstructor(CE, Pred, Dst);
782}
783
785 const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred,
786 ExplodedNodeSet &Dst) {
787 handleConstructor(CE, Pred, Dst);
788}
789
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(Engine.makeNode(PP, 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.
824 if (const Expr *E = dyn_cast_or_null<Expr>(S)) {
825 Dest = MRMgr.getCXXTempObjectRegion(E, Pred->getStackFrame());
826 } else {
827 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
828 Engine.makeNode(Pred->getLocation().withTag(&T), Pred->getState(), Pred,
829 /*MarkAsSink=*/true);
830 return;
831 }
832 }
833
836 DtorDecl, S, Dest, IsBaseDtor, State, SF, getCFGElementRef());
837
838 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
839 Call->getSourceRange().getBegin(),
840 "Error evaluating destructor");
841
842 ExplodedNodeSet DstPreCall;
843 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
844 *Call, *this);
845
846 ExplodedNodeSet DstInvalidated;
847 for (ExplodedNode *N : DstPreCall)
848 defaultEvalCall(DstInvalidated, N, *Call, CallOpts);
849
850 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
851 *Call, *this);
852}
853
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");
864 CEMgr.getCXXAllocatorCall(CNE, State, SF, getCFGElementRef());
865
866 ExplodedNodeSet DstPreCall;
867 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
868 *Call, *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(DstPostCall, I, *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(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(RetVal, 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(RetVal.castAs<DefinedOrUnknownSVal>(), true);
917 }
918
919 DstPostValue.insert(Engine.makePostStmtNode(
920 CNE, addObjectUnderConstruction(State, CNE, SF, RetVal), I));
921 }
922
923 ExplodedNodeSet DstPostPostCallCallback;
924 getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback,
925 DstPostValue, *Call, *this);
926 for (ExplodedNode *I : DstPostPostCallCallback) {
928 }
929}
930
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 =
945
946 ProgramStateRef State = Pred->getState();
947
948 // Retrieve the stored operator new() return value.
949 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) {
950 symVal = *getObjectUnderConstruction(State, CNE, SF);
951 State = finishObjectConstruction(State, 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(getCFGElementRef(), SF,
960 CNE->getType(), blockCount);
961 else
962 symVal = svalBuilder.conjureSymbolVal(
963 /*symbolTag=*/nullptr, getCFGElementRef(), SF, blockCount);
964 }
965
968 CEMgr.getCXXAllocatorCall(CNE, State, SF, 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, 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(*dSymVal, true);
990 }
991
992 SVal Result = symVal;
993
994 if (CNE->isArray()) {
995
996 if (const auto *NewReg = cast_or_null<SubRegion>(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>(Init);
1003
1004 QualType ObjTy =
1005 isInitList ? Init->getType() : CNE->getType()->getPointeeType();
1006 const ElementRegion *EleReg =
1007 MRMgr.getElementRegion(ObjTy, svalBuilder.makeArrayIndex(0), NewReg,
1008 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(CNE, State, Pred);
1015
1016 SVal V = State->getSVal(Init, SF);
1018 evalBind(Evaluated, CNE, Pred, Result, V, true);
1019
1020 for (ExplodedNode *N : Evaluated)
1021 Dst.insert(Engine.makeNodeWithBinding(N, CNE, Result));
1022 return;
1023 }
1024 }
1025
1026 Dst.insert(Engine.makeNodeWithBinding(Pred, CNE, 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.)
1035 // Non-array placement new should always return the placement location.
1036 SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), SF);
1037 Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
1038 CNE->getPlacementArg(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, CNE, Result, State);
1043 Dst.insert(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()) {
1051 assert(Dst.size() == 1);
1052 Dst.erase(NewN);
1053 evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, SF),
1054 /*FirstInit=*/IsStandardGlobalOpNewFunction);
1055 }
1056 }
1057}
1058
1060 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1061
1064 CDE, Pred->getState(), Pred->getStackFrame(), getCFGElementRef());
1065
1066 ExplodedNodeSet DstPreCall;
1067 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, *Call, *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(DstPostCall, I, *Call);
1077 }
1078 } else {
1079 DstPostCall = std::move(DstPreCall);
1080 }
1081 getCheckerManager().runCheckersForPostCall(Dst, DstPostCall, *Call, *this);
1082}
1083
1085 ExplodedNodeSet &Dst) {
1086 const VarDecl *VD = CS->getExceptionDecl();
1087 if (!VD) {
1088 Dst.insert(Pred);
1089 return;
1090 }
1091
1092 const StackFrame *SF = Pred->getStackFrame();
1093 SVal V = svalBuilder.conjureSymbolVal(getCFGElementRef(), SF, VD->getType(),
1095 ProgramStateRef state = Pred->getState();
1096 state = state->bindLoc(state->getLValue(VD, SF), V, SF);
1097
1098 Dst.insert(Engine.makePostStmtNode(CS, state, Pred));
1099}
1100
1102 ExplodedNode *Pred,
1103 ExplodedNodeSet &Dst) {
1104 ConstructInitList(E, E->getInitExprs(), /*IsTransparent*/ false, Pred, Dst);
1105}
1106
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 getContext().getCanonicalType(TE->getType()), SF);
1113
1114 ProgramStateRef state = Pred->getState();
1115 SVal V = state->getSVal(loc::MemRegionVal(R));
1116 Dst.insert(Engine.makeNodeWithBinding(Pred, TE, V));
1117}
1118
1120 ExplodedNodeSet &Dst) {
1121
1122 if (!AMgr.options.ShouldInlineLambdas) {
1123 const ExplodedNode *Node = Engine.makePostStmtNode(
1124 LE, Pred->getState(), Pred, /*MarkAsSink=*/true);
1125 Engine.addAbortedBlock(Node, 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(LE, SF);
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(llvm::seq<unsigned>(0, -1), LE->getLambdaClass()->fields(),
1142 LE->capture_inits())) {
1143 SVal FieldLoc = State->getLValue(FieldForCapture, 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 getContext().getAsConstantArrayType(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, {LE, Idx}, SF)) {
1163 InitVal = State->getSVal(OUC->getAsRegion());
1164
1165 State = finishObjectConstruction(State, {LE, Idx}, SF);
1166 } else
1167 InitVal = State->getSVal(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(SizeExpr, SF);
1179 }
1180
1181 State = State->bindLoc(FieldLoc, 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, LE, LambdaRVal, State,
1192
1193 // FIXME: Move all post/pre visits to ::Visit().
1194 getCheckerManager().runCheckersForPostStmt(Dst, N, LE, *this);
1195}
1196
1198 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1199 const StackFrame *SF = Pred->getStackFrame();
1200 ProgramStateRef State = Pred->getState();
1201
1202 for (const auto *Attr : getSpecificAttrs<CXXAssumeAttr>(A->getAttrs())) {
1203 SVal AssumedVal = State->getSVal(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(*ValidAssumedVal, true);
1208 }
1209
1210 if (!State)
1211 break;
1212 }
1213
1214 if (State)
1215 Dst.insert(Engine.makePostStmtNode(A, State, Pred));
1216}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static ProgramStateRef bindRequiredArrayElementToEnvironment(ProgramStateRef State, const ArrayInitLoopExpr *AILE, const StackFrame *SF, NonLoc Idx)
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
static uint64_t getConstantArrayElementCount(const ConstantArrayType *CA)
Return number of (potentially nested) constant array elements.
static uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE)
Return number of elements initialized in a (potentially nested) ArrayInitLoopExpr.
CFG::BuildOptions & getCFGBuildOptions()
Represents a loop initializing the elements of an array.
Definition Expr.h:6018
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6033
Attr - This represents one attribute.
Definition Attr.h:46
Represents an attribute applied to a statement.
Definition Stmt.h:2215
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2247
Represents a function call that returns a C++ object by value.
Definition CFG.h:190
std::optional< T > getAs() const
Convert to the specified CFGElement type, returning std::nullopt if this CFGElement is not of the des...
Definition CFG.h:113
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
VarDecl * getExceptionDecl() const
Definition StmtCXX.h:50
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1755
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
bool isArray() const
Definition ExprCXX.h:2468
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
SourceLocation getBeginLoc() const
Definition ExprCXX.h:2610
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5194
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5234
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1195
Represents the this expression in C++.
Definition ExprCXX.h:1158
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
ConstructionContext's subclasses describe different ways of constructing an object in C++.
virtual const ArrayInitLoopExpr * getArrayInitLoop() const
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:113
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
QualType getType() const
Definition Expr.h:145
Represents a function declaration or definition.
Definition Decl.h:2059
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions:
Definition Decl.h:2723
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition Decl.cpp:3447
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5385
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4973
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4998
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4990
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5023
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1248
Stmt * getParent(Stmt *) const
Represents a program point just after an implicit call event.
If a crash happens while one of these objects are live, the message is printed out along with the spe...
ProgramPoint withTag(const ProgramPointTag *tag) const
Create a new ProgramPoint object that is the same as the original except for using the specified tag ...
A (possibly-)qualified type.
Definition TypeBase.h:938
Represents a struct/union/class.
Definition Decl.h:4460
It represents a stack frame of the call stack.
const ParentMap & getParentMap() const
unsigned getIndex() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const Expr * getCallSite() const
const Decl * getDecl() const
const StackFrame * getParent() const
It might return null.
const CFGBlock * getCallSiteBlock() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8754
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9254
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
Represents a call to a C++ constructor.
Definition CallEvent.h:990
Manages the lifetime of CallEvent objects.
Definition CallEvent.h:1363
CallEventRef< CXXConstructorCall > getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1440
CallEventRef< CXXAllocatorCall > getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1464
CallEventRef< CXXInheritedConstructorCall > getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E, const MemRegion *Target, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1447
CallEventRef< CXXDeallocatorCall > getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1471
CallEventRef< CXXDestructorCall > getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, const MemRegion *Target, bool IsBase, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1455
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1433
CallEventRef getSimpleCall(const CallExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:152
static bool isVariadic(const Decl *D)
Returns true if the given decl is known to be variadic.
void runCheckersForPreCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng)
Run checkers for pre-visiting function calls (including methods, constructors, destructors etc.
void runCheckersForEvalCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &CE, ExprEngine &Eng, const EvalCallOptions &CallOpts)
Run checkers for evaluating a call.
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
void runCheckersForNewAllocator(const CXXAllocatorCall &Call, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, bool wasInlined=false)
Run checkers between C++ operator new and constructor calls.
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
void runCheckersForPostCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting function calls (including methods, constructors, destructors etc.
ElementRegion is used to represent both array elements and casts.
Definition MemRegion.h:1237
ExplodedNodeSet is a set of ExplodedNode * elements with the invariant that its elements cannot be nu...
void insert(ExplodedNode *N)
bool erase(ExplodedNode *N)
const ProgramStateRef & getState() const
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
const StackFrame * getStackFrame() const
ProgramStateManager & getStateManager()
Definition ExprEngine.h:441
void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst, EvalCallOptions &Options)
void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLambdaExpr - Transfer function logic for LambdaExprs.
CFGElement getCurrentCFGElement()
Return the CFG element corresponding to the worklist element that is currently being processed by Exp...
Definition ExprEngine.h:740
static std::optional< unsigned > getIndexOfElementToConstruct(ProgramStateRef State, const CXXConstructExpr *E, const StackFrame *SF)
Retrieves which element is being constructed in a non-POD type array.
ProgramStateRef bindReturnValue(const CallEvent &Call, const StackFrame *SF, ProgramStateRef State)
Create a new state in which the call return value is binded to the call origin expression.
static std::optional< unsigned > getPendingInitLoop(ProgramStateRef State, const CXXConstructExpr *E, const StackFrame *SF)
Retrieves the size of the array in the pending ArrayInitLoopExpr.
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition ExprEngine.h:192
StoreManager & getStoreManager()
Definition ExprEngine.h:444
void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
ProgramStateRef updateObjectsUnderConstruction(SVal V, const Expr *E, ProgramStateRef State, const StackFrame *SF, const ConstructionContext *CC, const EvalCallOptions &CallOpts)
Update the program state with all the path-sensitive information that's necessary to perform construc...
void defaultEvalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, const CallEvent &Call, const EvalCallOptions &CallOpts={})
Default implementation of call evaluation.
ConstCFGElementRef getCFGElementRef() const
Definition ExprEngine.h:254
void VisitCXXParenListInitExpr(const CXXParenListInitExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void ConstructInitList(const Expr *Source, ArrayRef< Expr * > Args, bool IsTransparent, ExplodedNode *Pred, ExplodedNodeSet &Dst)
std::pair< ProgramStateRef, SVal > handleConstructionContext(const Expr *E, ProgramStateRef State, const StackFrame *SF, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
A convenient wrapper around computeObjectUnderConstruction and updateObjectsUnderConstruction.
Definition ExprEngine.h:789
CheckerManager & getCheckerManager() const
Definition ExprEngine.h:201
static std::optional< SVal > getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const StackFrame *SF)
By looking at a certain item that may be potentially part of an object's ConstructionContext,...
SVal computeObjectUnderConstruction(const Expr *E, ProgramStateRef State, unsigned NumVisitedCaller, const StackFrame *SF, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
Find location of the object that is being constructed by a given constructor.
void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *MTE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Create a C++ temporary object for an rvalue.
unsigned getNumVisitedCurrent() const
Definition ExprEngine.h:263
void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
SValBuilder & getSValBuilder()
Definition ExprEngine.h:205
void VisitAttributedStmt(const AttributedStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitAttributedStmt - Transfer function logic for AttributedStmt.
const CFGBlock * getCurrBlock() const
Get the 'current' CFGBlock corresponding to the current work item (elementary analysis step handled b...
Definition ExprEngine.h:252
unsigned getNumVisited(const StackFrame *SF, const CFGBlock *Block) const
Definition ExprEngine.h:258
const ElementRegion * getElementRegion(QualType elementType, NonLoc Idx, const SubRegion *superRegion, const ASTContext &Ctx)
getElementRegion - Retrieve the memory region associated with the associated element type,...
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
CallEventManager & getCallEventManager()
MemRegionManager & getRegionManager()
ProgramStateManager & getStateManager()
NonLoc makeArrayIndex(uint64_t idx)
ASTContext & getContext()
loc::MemRegionVal makeLoc(SymbolRef sym)
loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrame *SF)
Return a memory region for the 'this' object reference.
DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, ConstCFGElementRef elem, const StackFrame *SF, unsigned count)
Create a new symbol with a unique 'name'.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:88
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:84
bool isUnknown() const
Definition SVals.h:111
SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast)
Evaluates a chain of derived-to-base casts through the path specified in Cast.
Definition Store.cpp:254
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:480
TypedValueRegion - An abstract class representing regions having a typed value.
Definition MemRegion.h:569
Definition ARM.cpp:1102
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
CXXConstructionKind
Definition ExprCXX.h:1544
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition Specifiers.h:338
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:341
@ SD_Static
Static storage duration.
Definition Specifiers.h:342
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:339
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
auto getSpecificAttrs(const Container &container)
U cast(CodeGen::Address addr)
Definition Address.h:327
Expr * extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE)
Definition CFG.cpp:1461
unsigned long uint64_t
Hints for figuring out if a call should be inlined during evalCall().
Definition ExprEngine.h:92
bool IsTemporaryLifetimeExtendedViaAggregate
This call is a constructor for a temporary that is lifetime-extended by binding it to a reference-typ...
Definition ExprEngine.h:107
bool IsTemporaryCtorOrDtor
This call is a constructor or a destructor of a temporary value.
Definition ExprEngine.h:102
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:99
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:114
bool IsCtorOrDtorWithImproperlyModeledTargetRegion
This call is a constructor or a destructor for which we do not currently compute the this-region corr...
Definition ExprEngine.h:95