clang 24.0.0git
ExprEngine.cpp
Go to the documentation of this file.
1//===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
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 a meta-engine for path-sensitive dataflow analysis that
10// is built on CoreEngine, but provides the boilerplate to execute transfer
11// functions and build the ExplodedGraph at the expression level.
12//
13//===----------------------------------------------------------------------===//
14
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ParentMap.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
30#include "clang/AST/Type.h"
32#include "clang/Analysis/CFG.h"
37#include "clang/Basic/LLVM.h"
64#include "llvm/ADT/APSInt.h"
65#include "llvm/ADT/DenseMap.h"
66#include "llvm/ADT/ImmutableMap.h"
67#include "llvm/ADT/ImmutableSet.h"
68#include "llvm/ADT/STLExtras.h"
69#include "llvm/ADT/SmallVector.h"
70#include "llvm/Support/Casting.h"
71#include "llvm/Support/Compiler.h"
72#include "llvm/Support/DOTGraphTraits.h"
73#include "llvm/Support/ErrorHandling.h"
74#include "llvm/Support/GraphWriter.h"
75#include "llvm/Support/IOSandbox.h"
76#include "llvm/Support/TimeProfiler.h"
77#include "llvm/Support/raw_ostream.h"
78#include <cassert>
79#include <cstdint>
80#include <memory>
81#include <optional>
82#include <string>
83#include <tuple>
84#include <utility>
85#include <vector>
86
87using namespace clang;
88using namespace ento;
89
90#define DEBUG_TYPE "ExprEngine"
91
92STAT_COUNTER(NumRemoveDeadBindings,
93 "The # of times RemoveDeadBindings is called");
95 NumMaxBlockCountReached,
96 "The # of aborted paths due to reaching the maximum block count in "
97 "a top level function");
99 NumMaxBlockCountReachedInInlined,
100 "The # of aborted paths due to reaching the maximum block count in "
101 "an inlined function");
102STAT_COUNTER(NumTimesRetriedWithoutInlining,
103 "The # of times we re-evaluated a call without inlining");
104
105//===----------------------------------------------------------------------===//
106// Internal program state traits.
107//===----------------------------------------------------------------------===//
108
109namespace {
110
111// When modeling a C++ constructor, for a variety of reasons we need to track
112// the location of the object for the duration of its ConstructionContext.
113// ObjectsUnderConstruction maps statements within the construction context
114// to the object's location, so that on every such statement the location
115// could have been retrieved.
116
117/// ConstructedObjectKey is used for being able to find the path-sensitive
118/// memory region of a freshly constructed object while modeling the AST node
119/// that syntactically represents the object that is being constructed.
120/// Semantics of such nodes may sometimes require access to the region that's
121/// not otherwise present in the program state, or to the very fact that
122/// the construction context was present and contained references to these
123/// AST nodes.
124class ConstructedObjectKey {
125 using ConstructedObjectKeyImpl =
126 std::pair<ConstructionContextItem, const StackFrame *>;
127 const ConstructedObjectKeyImpl Impl;
128
129public:
130 explicit ConstructedObjectKey(const ConstructionContextItem &Item,
131 const StackFrame *SF)
132 : Impl(Item, SF) {}
133
134 const ConstructionContextItem &getItem() const { return Impl.first; }
135 const StackFrame *getStackFrame() const { return Impl.second; }
136
137 ASTContext &getASTContext() const {
138 return getStackFrame()->getDecl()->getASTContext();
139 }
140
141 void printJson(llvm::raw_ostream &Out, PrinterHelper *Helper,
142 PrintingPolicy &PP) const {
143 const Stmt *S = getItem().getStmtOrNull();
144 const CXXCtorInitializer *I = nullptr;
145 if (!S)
146 I = getItem().getCXXCtorInitializer();
147
148 if (S)
149 Out << "\"stmt_id\": " << S->getID(getASTContext());
150 else
151 Out << "\"init_id\": " << I->getID(getASTContext());
152
153 // Kind
154 Out << ", \"kind\": \"" << getItem().getKindAsString()
155 << "\", \"argument_index\": ";
156
158 Out << getItem().getIndex();
159 else
160 Out << "null";
161
162 // Pretty-print
163 Out << ", \"pretty\": ";
164
165 if (S) {
166 S->printJson(Out, Helper, PP, /*AddQuotes=*/true);
167 } else {
168 Out << '\"' << I->getAnyMember()->getDeclName() << '\"';
169 }
170 }
171
172 void Profile(llvm::FoldingSetNodeID &ID) const {
173 ID.Add(Impl.first);
174 ID.AddPointer(Impl.second);
175 }
176
177 bool operator==(const ConstructedObjectKey &RHS) const {
178 return Impl == RHS.Impl;
179 }
180
181 bool operator<(const ConstructedObjectKey &RHS) const {
182 return Impl < RHS.Impl;
183 }
184};
185} // namespace
186
187typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
189REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
191
192// This trait is responsible for storing the index of the element that is to be
193// constructed in the next iteration. As a result a CXXConstructExpr is only
194// stored if it is array type. Also the index is the index of the continuous
195// memory region, which is important for multi-dimensional arrays. E.g:: int
196// arr[2][2]; assume arr[1][1] will be the next element under construction, so
197// the index is 3.
198typedef llvm::ImmutableMap<
199 std::pair<const CXXConstructExpr *, const StackFrame *>, unsigned>
200 IndexOfElementToConstructMap;
201REGISTER_TRAIT_WITH_PROGRAMSTATE(IndexOfElementToConstruct,
202 IndexOfElementToConstructMap)
203
204// This trait is responsible for holding our pending ArrayInitLoopExprs.
205// It pairs the StackFrame and the initializer CXXConstructExpr with
206// the size of the array that's being copy initialized.
207typedef llvm::ImmutableMap<
208 std::pair<const CXXConstructExpr *, const StackFrame *>, unsigned>
209 PendingInitLoopMap;
210REGISTER_TRAIT_WITH_PROGRAMSTATE(PendingInitLoop, PendingInitLoopMap)
211
212typedef llvm::ImmutableMap<const StackFrame *, unsigned>
214REGISTER_TRAIT_WITH_PROGRAMSTATE(PendingArrayDestruction,
216
217//===----------------------------------------------------------------------===//
218// Engine construction and deletion.
219//===----------------------------------------------------------------------===//
220
221static const char* TagProviderName = "ExprEngine";
222
224 AnalysisManager &mgr, SetOfConstDecls *VisitedCalleesIn,
225 FunctionSummariesTy *FS, InliningModes HowToInlineIn)
226 : CTU(CTU), IsCTUEnabled(mgr.getAnalyzerOptions().IsNaiveCTUEnabled),
227 AMgr(mgr), AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
228 Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
229 StateMgr(getContext(), mgr.getStoreManagerCreator(),
230 mgr.getConstraintManagerCreator(), G.getAllocator(), this),
231 SymMgr(StateMgr.getSymbolManager()), MRMgr(StateMgr.getRegionManager()),
232 svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
233 BR(mgr, *this), VisitedCallees(VisitedCalleesIn),
234 HowToInline(HowToInlineIn) {
235 unsigned TrimInterval = mgr.options.GraphTrimInterval;
236 if (TrimInterval != 0) {
237 // Enable eager node reclamation when constructing the ExplodedGraph.
238 G.enableNodeReclamation(TrimInterval);
239 }
240}
241
242//===----------------------------------------------------------------------===//
243// Utility methods.
244//===----------------------------------------------------------------------===//
245
247 ProgramStateRef state = StateMgr.getInitialState(InitSF);
248 const Decl *D = InitSF->getDecl();
249
250 // Preconditions.
251 // FIXME: It would be nice if we had a more general mechanism to add
252 // such preconditions. Some day.
253 do {
254 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
255 // Precondition: the first argument of 'main' is an integer guaranteed
256 // to be > 0.
257 const IdentifierInfo *II = FD->getIdentifier();
258 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
259 break;
260
261 const ParmVarDecl *PD = FD->getParamDecl(0);
262 QualType T = PD->getType();
263 const auto *BT = dyn_cast<BuiltinType>(T);
264 if (!BT || !BT->isInteger())
265 break;
266
267 const MemRegion *R = state->getRegion(PD, InitSF);
268 if (!R)
269 break;
270
271 SVal V = state->getSVal(loc::MemRegionVal(R));
272 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
273 svalBuilder.makeZeroVal(T),
274 svalBuilder.getConditionType());
275
276 std::optional<DefinedOrUnknownSVal> Constraint =
277 Constraint_untested.getAs<DefinedOrUnknownSVal>();
278
279 if (!Constraint)
280 break;
281
282 if (ProgramStateRef newState = state->assume(*Constraint, true))
283 state = newState;
284 }
285 break;
286 }
287 while (false);
288
289 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
290 // Precondition: 'self' is always non-null upon entry to an Objective-C
291 // method.
292 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
293 const MemRegion *R = state->getRegion(SelfD, InitSF);
294 SVal V = state->getSVal(loc::MemRegionVal(R));
295
296 if (std::optional<Loc> LV = V.getAs<Loc>()) {
297 // Assume that the pointer value in 'self' is non-null.
298 state = state->assume(*LV, true);
299 assert(state && "'self' cannot be null");
300 }
301 }
302
303 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
304 if (MD->isImplicitObjectMemberFunction()) {
305 // Precondition: 'this' is always non-null upon entry to the
306 // top-level function. This is our starting assumption for
307 // analyzing an "open" program.
308 const StackFrame *SF = InitSF;
309 if (SF->getParent() == nullptr) {
310 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SF);
311 SVal V = state->getSVal(L);
312 if (std::optional<Loc> LV = V.getAs<Loc>()) {
313 state = state->assume(*LV, true);
314 assert(state && "'this' cannot be null");
315 }
316 }
317 }
318 }
319
320 return state;
321}
322
323ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded(
324 ProgramStateRef State, const StackFrame *SF,
325 const Expr *InitWithAdjustments, const Expr *Result,
326 const SubRegion **OutRegionWithAdjustments) {
327 // FIXME: This function is a hack that works around the quirky AST
328 // we're often having with respect to C++ temporaries. If only we modelled
329 // the actual execution order of statements properly in the CFG,
330 // all the hassle with adjustments would not be necessary,
331 // and perhaps the whole function would be removed.
332 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, SF);
333 if (!Result) {
334 // If we don't have an explicit result expression, we're in "if needed"
335 // mode. Only create a region if the current value is a NonLoc.
336 if (!isa<NonLoc>(InitValWithAdjustments)) {
337 if (OutRegionWithAdjustments)
338 *OutRegionWithAdjustments = nullptr;
339 return State;
340 }
341 Result = InitWithAdjustments;
342 } else {
343 // We need to create a region no matter what. Make sure we don't try to
344 // stuff a Loc into a non-pointer temporary region.
345 assert(!isa<Loc>(InitValWithAdjustments) ||
346 Loc::isLocType(Result->getType()) ||
347 Result->getType()->isMemberPointerType());
348 }
349
350 ProgramStateManager &StateMgr = State->getStateManager();
351 MemRegionManager &MRMgr = StateMgr.getRegionManager();
352 StoreManager &StoreMgr = StateMgr.getStoreManager();
353
354 // MaterializeTemporaryExpr may appear out of place, after a few field and
355 // base-class accesses have been made to the object, even though semantically
356 // it is the whole object that gets materialized and lifetime-extended.
357 //
358 // For example:
359 //
360 // `-MaterializeTemporaryExpr
361 // `-MemberExpr
362 // `-CXXTemporaryObjectExpr
363 //
364 // instead of the more natural
365 //
366 // `-MemberExpr
367 // `-MaterializeTemporaryExpr
368 // `-CXXTemporaryObjectExpr
369 //
370 // Use the usual methods for obtaining the expression of the base object,
371 // and record the adjustments that we need to make to obtain the sub-object
372 // that the whole expression 'Ex' refers to. This trick is usual,
373 // in the sense that CodeGen takes a similar route.
374
375 SmallVector<const Expr *, 2> CommaLHSs;
376 SmallVector<SubobjectAdjustment, 2> Adjustments;
377
378 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
379 CommaLHSs, Adjustments);
380
381 // Take the region for Init, i.e. for the whole object. If we do not remember
382 // the region in which the object originally was constructed, come up with
383 // a new temporary region out of thin air and copy the contents of the object
384 // (which are currently present in the Environment, because Init is an rvalue)
385 // into that region. This is not correct, but it is better than nothing.
386 const TypedValueRegion *TR = nullptr;
387 if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
388 if (std::optional<SVal> V = getObjectUnderConstruction(State, MT, SF)) {
389 State = finishObjectConstruction(State, MT, SF);
390 State = State->BindExpr(Result, SF, *V);
391 return State;
392 } else if (const ValueDecl *VD = MT->getExtendingDecl()) {
393 StorageDuration SD = MT->getStorageDuration();
394 assert(SD != SD_FullExpression);
395 // If this object is bound to a reference with static storage duration, we
396 // put it in a different region to prevent "address leakage" warnings.
397 if (SD == SD_Static || SD == SD_Thread) {
398 TR = MRMgr.getCXXStaticLifetimeExtendedObjectRegion(Init, VD);
399 } else {
400 TR = MRMgr.getCXXLifetimeExtendedObjectRegion(Init, VD, SF);
401 }
402 } else {
403 assert(MT->getStorageDuration() == SD_FullExpression);
404 TR = MRMgr.getCXXTempObjectRegion(Init, SF);
405 }
406 } else {
407 TR = MRMgr.getCXXTempObjectRegion(Init, SF);
408 }
409
410 SVal Reg = loc::MemRegionVal(TR);
411 SVal BaseReg = Reg;
412
413 // Make the necessary adjustments to obtain the sub-object.
414 for (const SubobjectAdjustment &Adj : llvm::reverse(Adjustments)) {
415 switch (Adj.Kind) {
417 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
418 break;
420 Reg = StoreMgr.getLValueField(Adj.Field, Reg);
421 break;
423 // FIXME: Unimplemented.
424 State = State->invalidateRegions(Reg, getCFGElementRef(),
425 getNumVisitedCurrent(), SF, true,
426 nullptr, nullptr, nullptr);
427 return State;
428 }
429 }
430
431 // What remains is to copy the value of the object to the new region.
432 // FIXME: In other words, what we should always do is copy value of the
433 // Init expression (which corresponds to the bigger object) to the whole
434 // temporary region TR. However, this value is often no longer present
435 // in the Environment. If it has disappeared, we instead invalidate TR.
436 // Still, what we can do is assign the value of expression Ex (which
437 // corresponds to the sub-object) to the TR's sub-region Reg. At least,
438 // values inside Reg would be correct.
439 SVal InitVal = State->getSVal(Init, SF);
440 if (InitVal.isUnknown()) {
442 getCFGElementRef(), SF, Init->getType(), getNumVisitedCurrent());
443 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, SF, false);
444
445 // Then we'd need to take the value that certainly exists and bind it
446 // over.
447 if (InitValWithAdjustments.isUnknown()) {
448 // Try to recover some path sensitivity in case we couldn't
449 // compute the value.
450 InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
451 getCFGElementRef(), SF, InitWithAdjustments->getType(),
453 }
454 State =
455 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, SF, false);
456 } else {
457 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, SF, false);
458 }
459
460 // The result expression would now point to the correct sub-region of the
461 // newly created temporary region. Do this last in order to getSVal of Init
462 // correctly in case (Result == Init).
463 if (Result->isGLValue()) {
464 State = State->BindExpr(Result, SF, Reg);
465 } else {
466 State = State->BindExpr(Result, SF, InitValWithAdjustments);
467 }
468
469 // Notify checkers once for two bindLoc()s.
470 State = processRegionChange(State, TR, SF);
471
472 if (OutRegionWithAdjustments)
473 *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion());
474 return State;
475}
476
478ExprEngine::setIndexOfElementToConstruct(ProgramStateRef State,
479 const CXXConstructExpr *E,
480 const StackFrame *SF, unsigned Idx) {
481 auto Key = std::make_pair(E, SF);
482
483 assert(!State->contains<IndexOfElementToConstruct>(Key) || Idx > 0);
484
485 return State->set<IndexOfElementToConstruct>(Key, Idx);
486}
487
488std::optional<unsigned>
490 const StackFrame *SF) {
491 const unsigned *V = State->get<PendingInitLoop>({E, SF});
492 return V ? std::make_optional(*V) : std::nullopt;
493}
494
495ProgramStateRef ExprEngine::removePendingInitLoop(ProgramStateRef State,
496 const CXXConstructExpr *E,
497 const StackFrame *SF) {
498 auto Key = std::make_pair(E, SF);
499
500 assert(E && State->contains<PendingInitLoop>(Key));
501 return State->remove<PendingInitLoop>(Key);
502}
503
504ProgramStateRef ExprEngine::setPendingInitLoop(ProgramStateRef State,
505 const CXXConstructExpr *E,
506 const StackFrame *SF,
507 unsigned Size) {
508 auto Key = std::make_pair(E, SF);
509
510 assert(!State->contains<PendingInitLoop>(Key) && Size > 0);
511
512 return State->set<PendingInitLoop>(Key, Size);
513}
514
516 ProgramStateRef State, const CXXConstructExpr *E, const StackFrame *SF) {
517 const unsigned *V = State->get<IndexOfElementToConstruct>({E, SF});
518 return V ? std::make_optional(*V) : std::nullopt;
519}
520
521ProgramStateRef ExprEngine::removeIndexOfElementToConstruct(
522 ProgramStateRef State, const CXXConstructExpr *E, const StackFrame *SF) {
523 auto Key = std::make_pair(E, SF);
524
525 assert(E && State->contains<IndexOfElementToConstruct>(Key));
526 return State->remove<IndexOfElementToConstruct>(Key);
527}
528
529std::optional<unsigned>
531 const StackFrame *SF) {
532 assert(SF && "StackFrame shouldn't be null!");
533
534 const unsigned *V = State->get<PendingArrayDestruction>(SF);
535 return V ? std::make_optional(*V) : std::nullopt;
536}
537
538ProgramStateRef ExprEngine::setPendingArrayDestruction(ProgramStateRef State,
539 const StackFrame *SF,
540 unsigned Idx) {
541 assert(SF && "StackFrame shouldn't be null!");
542 return State->set<PendingArrayDestruction>(SF, Idx);
543}
544
546ExprEngine::removePendingArrayDestruction(ProgramStateRef State,
547 const StackFrame *SF) {
548 assert(SF && "StackFrame shouldn't be null!");
549 assert(State->contains<PendingArrayDestruction>(SF));
550 return State->remove<PendingArrayDestruction>(SF);
551}
552
554ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
555 const ConstructionContextItem &Item,
556 const StackFrame *SF, SVal V) {
557 ConstructedObjectKey Key(Item, SF);
558
559 const Expr *Init = nullptr;
560
561 if (auto DS = dyn_cast_or_null<DeclStmt>(Item.getStmtOrNull())) {
562 if (auto VD = dyn_cast_or_null<VarDecl>(DS->getSingleDecl()))
563 Init = VD->getInit();
564 }
565
566 if (auto LE = dyn_cast_or_null<LambdaExpr>(Item.getStmtOrNull()))
567 Init = *(LE->capture_init_begin() + Item.getIndex());
568
569 if (!Init && !Item.getStmtOrNull())
571
572 // In an ArrayInitLoopExpr the real initializer is returned by
573 // getSubExpr(). Note that AILEs can be nested in case of
574 // multidimesnional arrays.
575 if (const auto *AILE = dyn_cast_or_null<ArrayInitLoopExpr>(Init))
577
578 // FIXME: Currently the state might already contain the marker due to
579 // incorrect handling of temporaries bound to default parameters.
580 // The state will already contain the marker if we construct elements
581 // in an array, as we visit the same statement multiple times before
582 // the array declaration. The marker is removed when we exit the
583 // constructor call.
584 assert((!State->get<ObjectsUnderConstruction>(Key) ||
585 Key.getItem().getKind() ==
587 State->contains<IndexOfElementToConstruct>(
588 {dyn_cast_or_null<CXXConstructExpr>(Init), SF})) &&
589 "The object is already marked as `UnderConstruction`, when it's not "
590 "supposed to!");
591 return State->set<ObjectsUnderConstruction>(Key, V);
592}
593
594std::optional<SVal>
596 const ConstructionContextItem &Item,
597 const StackFrame *SF) {
598 ConstructedObjectKey Key(Item, SF);
599 const SVal *V = State->get<ObjectsUnderConstruction>(Key);
600 return V ? std::make_optional(*V) : std::nullopt;
601}
602
604ExprEngine::finishObjectConstruction(ProgramStateRef State,
605 const ConstructionContextItem &Item,
606 const StackFrame *SF) {
607 ConstructedObjectKey Key(Item, SF);
608 assert(State->contains<ObjectsUnderConstruction>(Key));
609 return State->remove<ObjectsUnderConstruction>(Key);
610}
611
612ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
613 const CXXBindTemporaryExpr *BTE,
614 const StackFrame *SF) {
615 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, SF);
616 // FIXME: Currently the state might already contain the marker due to
617 // incorrect handling of temporaries bound to default parameters.
618 return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
619}
620
622ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
623 const CXXBindTemporaryExpr *BTE,
624 const StackFrame *SF) {
625 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, SF);
626 assert(State->contains<ObjectsUnderConstruction>(Key));
627 return State->remove<ObjectsUnderConstruction>(Key);
628}
629
630bool ExprEngine::isDestructorElided(ProgramStateRef State,
631 const CXXBindTemporaryExpr *BTE,
632 const StackFrame *SF) {
633 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, SF);
634 return State->contains<ObjectsUnderConstruction>(Key);
635}
636
637bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
638 const StackFrame *FromSF,
639 const StackFrame *ToSF) {
640 const StackFrame *SF = FromSF;
641 while (SF != ToSF) {
642 assert(SF && "ToSF must be a parent of FromSF!");
643 for (auto I : State->get<ObjectsUnderConstruction>())
644 if (I.first.getStackFrame() == SF)
645 return false;
646
647 SF = SF->getParent();
648 }
649 return true;
650}
651
652//===----------------------------------------------------------------------===//
653// Top-level transfer function logic (Dispatcher).
654//===----------------------------------------------------------------------===//
655
656/// evalAssume - Called by ConstraintManager. Used to call checker-specific
657/// logic for handling assumptions on symbolic values.
659 SVal cond, bool assumption) {
660 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
661}
662
664 ProgramStateRef state, const InvalidatedSymbols *invalidated,
666 const StackFrame *SF, const CallEvent *Call) {
668 state, invalidated, Explicits, Regions, SF, Call);
669}
670
671static void
673 const char *NL, const StackFrame *SF,
674 unsigned int Space = 0, bool IsDot = false) {
675 PrintingPolicy PP =
677
678 ++Space;
679 bool HasItem = false;
680
681 // Store the last key.
682 const ConstructedObjectKey *LastKey = nullptr;
683 for (const auto &I : State->get<ObjectsUnderConstruction>()) {
684 const ConstructedObjectKey &Key = I.first;
685 if (Key.getStackFrame() != SF)
686 continue;
687
688 if (!HasItem) {
689 Out << '[' << NL;
690 HasItem = true;
691 }
692
693 LastKey = &Key;
694 }
695
696 for (const auto &I : State->get<ObjectsUnderConstruction>()) {
697 const ConstructedObjectKey &Key = I.first;
698 SVal Value = I.second;
699 if (Key.getStackFrame() != SF)
700 continue;
701
702 Indent(Out, Space, IsDot) << "{ ";
703 Key.printJson(Out, nullptr, PP);
704 Out << ", \"value\": \"" << Value << "\" }";
705
706 if (&Key != LastKey)
707 Out << ',';
708 Out << NL;
709 }
710
711 if (HasItem)
712 Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
713 else {
714 Out << "null ";
715 }
716}
717
719 raw_ostream &Out, ProgramStateRef State, const char *NL,
720 const StackFrame *SF, unsigned int Space = 0, bool IsDot = false) {
721 using KeyT = std::pair<const Expr *, const StackFrame *>;
722
723 const auto &Context = SF->getAnalysisDeclContext()->getASTContext();
724 PrintingPolicy PP = Context.getPrintingPolicy();
725
726 ++Space;
727 bool HasItem = false;
728
729 // Store the last key.
730 KeyT LastKey;
731 for (const auto &I : State->get<IndexOfElementToConstruct>()) {
732 const KeyT &Key = I.first;
733 if (Key.second != SF)
734 continue;
735
736 if (!HasItem) {
737 Out << '[' << NL;
738 HasItem = true;
739 }
740
741 LastKey = Key;
742 }
743
744 for (const auto &I : State->get<IndexOfElementToConstruct>()) {
745 const KeyT &Key = I.first;
746 unsigned Value = I.second;
747 if (Key.second != SF)
748 continue;
749
750 Indent(Out, Space, IsDot) << "{ ";
751
752 // Expr
753 const Expr *E = Key.first;
754 Out << "\"stmt_id\": " << E->getID(Context);
755
756 // Kind
757 Out << ", \"kind\": null";
758
759 // Pretty-print
760 Out << ", \"pretty\": ";
761 Out << "\"" << E->getStmtClassName() << ' '
762 << E->getSourceRange().printToString(Context.getSourceManager()) << " '"
763 << QualType::getAsString(E->getType().split(), PP);
764 Out << "'\"";
765
766 Out << ", \"value\": \"Current index: " << Value - 1 << "\" }";
767
768 if (Key != LastKey)
769 Out << ',';
770 Out << NL;
771 }
772
773 if (HasItem)
774 Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
775 else {
776 Out << "null ";
777 }
778}
779
780static void printPendingInitLoopJson(raw_ostream &Out, ProgramStateRef State,
781 const char *NL, const StackFrame *SF,
782 unsigned int Space = 0,
783 bool IsDot = false) {
784 using KeyT = std::pair<const CXXConstructExpr *, const StackFrame *>;
785
786 const auto &Context = SF->getAnalysisDeclContext()->getASTContext();
787 PrintingPolicy PP = Context.getPrintingPolicy();
788
789 ++Space;
790 bool HasItem = false;
791
792 // Store the last key.
793 KeyT LastKey;
794 for (const auto &I : State->get<PendingInitLoop>()) {
795 const KeyT &Key = I.first;
796 if (Key.second != SF)
797 continue;
798
799 if (!HasItem) {
800 Out << '[' << NL;
801 HasItem = true;
802 }
803
804 LastKey = Key;
805 }
806
807 for (const auto &I : State->get<PendingInitLoop>()) {
808 const KeyT &Key = I.first;
809 unsigned Value = I.second;
810 if (Key.second != SF)
811 continue;
812
813 Indent(Out, Space, IsDot) << "{ ";
814
815 const CXXConstructExpr *E = Key.first;
816 Out << "\"stmt_id\": " << E->getID(Context);
817
818 Out << ", \"kind\": null";
819 Out << ", \"pretty\": ";
820 Out << '\"' << E->getStmtClassName() << ' '
821 << E->getSourceRange().printToString(Context.getSourceManager()) << " '"
822 << QualType::getAsString(E->getType().split(), PP);
823 Out << "'\"";
824
825 Out << ", \"value\": \"Flattened size: " << Value << "\"}";
826
827 if (Key != LastKey)
828 Out << ',';
829 Out << NL;
830 }
831
832 if (HasItem)
833 Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
834 else {
835 Out << "null ";
836 }
837}
838
839static void
841 const char *NL, const StackFrame *SF,
842 unsigned int Space = 0, bool IsDot = false) {
843 using KeyT = const StackFrame *;
844
845 ++Space;
846 bool HasItem = false;
847
848 // Store the last key.
849 KeyT LastKey = nullptr;
850 for (const auto &I : State->get<PendingArrayDestruction>()) {
851 const KeyT &Key = I.first;
852 if (Key != SF)
853 continue;
854
855 if (!HasItem) {
856 Out << '[' << NL;
857 HasItem = true;
858 }
859
860 LastKey = Key;
861 }
862
863 for (const auto &I : State->get<PendingArrayDestruction>()) {
864 const KeyT &Key = I.first;
865 if (Key != SF)
866 continue;
867
868 Indent(Out, Space, IsDot) << "{ ";
869
870 Out << "\"stmt_id\": null";
871 Out << ", \"kind\": null";
872 Out << ", \"pretty\": \"Current index: \"";
873 Out << ", \"value\": \"" << I.second << "\" }";
874
875 if (Key != LastKey)
876 Out << ',';
877 Out << NL;
878 }
879
880 if (HasItem)
881 Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
882 else {
883 Out << "null ";
884 }
885}
886
887/// A helper function to generalize program state trait printing.
888/// The function invokes Printer as 'Printer(Out, State, NL, SF, Space, IsDot,
889/// std::forward<Args>(args)...)'. \n One possible type for Printer is
890/// 'void()(raw_ostream &, ProgramStateRef, const char *, const StackFrame *,
891/// unsigned int, bool, ...)' \n \param Trait The state trait to be printed.
892/// \param Printer A void function that prints Trait.
893/// \param Args An additional parameter pack that is passed to Print upon
894/// invocation.
895template <typename Trait, typename Printer, typename... Args>
897 raw_ostream &Out, ProgramStateRef State, const StackFrame *SF,
898 const char *NL, unsigned int Space, bool IsDot,
899 const char *jsonPropertyName, Printer printer, Args &&...args) {
900
901 using RequiredType =
902 void (*)(raw_ostream &, ProgramStateRef, const char *, const StackFrame *,
903 unsigned int, bool, Args &&...);
904
905 // Try to do as much compile time checking as possible.
906 // FIXME: check for invocable instead of function?
907 static_assert(std::is_function_v<std::remove_pointer_t<Printer>>,
908 "Printer is not a function!");
909 static_assert(std::is_convertible_v<Printer, RequiredType>,
910 "Printer doesn't have the required type!");
911
912 if (SF && !State->get<Trait>().isEmpty()) {
913 Indent(Out, Space, IsDot) << '\"' << jsonPropertyName << "\": ";
914 ++Space;
915 Out << '[' << NL;
916 SF->printJson(Out, NL, Space, IsDot, [&](const StackFrame *SF) {
917 printer(Out, State, NL, SF, Space, IsDot, std::forward<Args>(args)...);
918 });
919
920 --Space;
921 Indent(Out, Space, IsDot) << "]," << NL; // End of "jsonPropertyName".
922 }
923}
924
925void ExprEngine::printJson(raw_ostream &Out, ProgramStateRef State,
926 const StackFrame *SF, const char *NL,
927 unsigned int Space, bool IsDot) const {
928
930 Out, State, SF, NL, Space, IsDot, "constructing_objects",
933 Out, State, SF, NL, Space, IsDot, "index_of_element",
936 Out, State, SF, NL, Space, IsDot, "pending_init_loops",
939 Out, State, SF, NL, Space, IsDot, "pending_destructors",
941
942 getCheckerManager().runCheckersForPrintStateJson(Out, State, NL, Space,
943 IsDot);
944}
945
947 // This prints the name of the top-level function if we crash.
950}
951
953 unsigned StmtIdx) {
954 currStmtIdx = StmtIdx;
955
956 switch (E.getKind()) {
960 ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
961 return;
964 return;
967 Pred);
968 return;
975 return;
978 return;
981 E.castAs<CFGLifetimeEnds>().getVarDecl(), Pred);
982 return;
987 return;
988 }
989}
990
992 const ExplodedNode *Pred,
993 const StackFrame *SF) {
994 // Are we never purging state values?
995 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
996 return false;
997
998 // Is this the beginning of a basic block?
999 if (Pred->getLocation().getAs<BlockEntrance>())
1000 return true;
1001
1002 // Is this on a non-expression?
1003 if (!isa<Expr>(S))
1004 return true;
1005
1006 // Run before processing a call.
1007 if (CallEvent::isCallStmt(S))
1008 return true;
1009
1010 // Is this an expression that is consumed by another expression? If so,
1011 // postpone cleaning out the state.
1013 return !PM.isConsumedExpr(cast<Expr>(S));
1014}
1015
1017 const Stmt *ReferenceStmt, const StackFrame *SF,
1018 const Stmt *DiagnosticStmt, ProgramPoint::Kind K) {
1019 llvm::TimeTraceScope TimeScope("ExprEngine::removeDead");
1021 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
1022 && "PostStmt is not generally supported by the SymbolReaper yet");
1023 assert(SF && "Must pass the current (or expiring) StackFrame");
1024
1025 if (!DiagnosticStmt) {
1026 DiagnosticStmt = ReferenceStmt;
1027 assert(DiagnosticStmt && "Required for clearing a StackFrame");
1028 }
1029
1030 NumRemoveDeadBindings++;
1031 ProgramStateRef CleanedState = Pred->getState();
1032
1033 // SF is the stack frame being destroyed, but SymbolReaper wants a
1034 // stack frame that is still live. (If this is the top-level stack
1035 // frame, this will be null.)
1036 if (!ReferenceStmt) {
1038 "Use PostStmtPurgeDeadSymbolsKind for clearing a StackFrame");
1039 SF = SF->getParent();
1040 }
1041
1042 SymbolReaper SymReaper(SF, ReferenceStmt, SymMgr, getStoreManager());
1043
1044 for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
1045 if (SymbolRef Sym = I.second.getAsSymbol())
1046 SymReaper.markLive(Sym);
1047 if (const MemRegion *MR = I.second.getAsRegion())
1048 SymReaper.markLive(MR);
1049 }
1050
1051 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
1052
1053 // Create a state in which dead bindings are removed from the environment
1054 // and the store. TODO: The function should just return new env and store,
1055 // not a new state.
1056 CleanedState = StateMgr.removeDeadBindingsFromEnvironmentAndStore(
1057 CleanedState, SF, SymReaper);
1058
1059 // Process any special transfer function for dead symbols.
1060 // Call checkers with the non-cleaned state so that they could query the
1061 // values of the soon to be dead symbols.
1062 ExplodedNodeSet CheckedSet;
1063 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
1064 DiagnosticStmt, *this, K);
1065
1066 // Extend lifetime of symbols used for dynamic extent while the parent region
1067 // is live. In this way size information about memory allocations is not lost
1068 // if the region remains live.
1069 markAllDynamicExtentLive(CleanedState, SymReaper);
1070
1071 // For each node in CheckedSet, generate CleanedNodes that have the
1072 // environment, the store, and the constraints cleaned up but have the
1073 // user-supplied states as the predecessors.
1074 for (const auto I : CheckedSet) {
1075 ProgramStateRef CheckerState = I->getState();
1076
1077 // The constraint manager has not been cleaned up yet, so clean up now.
1078 CheckerState =
1079 getConstraintManager().removeDeadBindings(CheckerState, SymReaper);
1080
1081 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
1082 "Checkers are not allowed to modify the Environment as a part of "
1083 "checkDeadSymbols processing.");
1084 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
1085 "Checkers are not allowed to modify the Store as a part of "
1086 "checkDeadSymbols processing.");
1087
1088 // Create a state based on CleanedState with CheckerState GDM and
1089 // generate a transition to that state.
1090 ProgramStateRef CleanedCheckerSt =
1091 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
1093 DiagnosticStmt, K, I->getStackFrame(), cleanupNodeTag());
1094 Out.insert(Engine.makeNode(L, CleanedCheckerSt, I));
1095 }
1096}
1097
1099 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
1100 return &cleanupTag;
1101}
1102
1103void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
1104 // Reclaim any unnecessary nodes in the ExplodedGraph.
1105 G.reclaimRecentlyAllocatedNodes();
1106
1107 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1108 currStmt->getBeginLoc(),
1109 "Error evaluating statement");
1110
1111 // Remove dead bindings and symbols.
1112 ExplodedNodeSet CleanedStates;
1113 if (shouldRemoveDeadBindings(AMgr, currStmt, Pred, Pred->getStackFrame())) {
1114 removeDead(Pred, CleanedStates, currStmt, Pred->getStackFrame());
1115 } else
1116 CleanedStates.insert(Pred);
1117
1118 // Visit the statement.
1119 ExplodedNodeSet Dst;
1120 for (const auto I : CleanedStates) {
1121 ExplodedNodeSet DstI;
1122 // Visit the statement.
1123 Visit(currStmt, I, DstI);
1124 Dst.insert(DstI);
1125 }
1126
1127 // Enqueue the new nodes onto the work list.
1128 Engine.enqueueStmtNodes(Dst, getCurrBlock(), currStmtIdx);
1129}
1130
1132 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1133 S->getBeginLoc(),
1134 "Error evaluating end of the loop");
1135 ProgramStateRef NewState = Pred->getState();
1136
1137 if(AMgr.options.ShouldUnrollLoops)
1138 NewState = processLoopEnd(S, NewState);
1139
1140 LoopExit PP(S, Pred->getStackFrame());
1141 ExplodedNode *N = Engine.makeNode(PP, NewState, Pred);
1142 if (N && !N->isSink())
1143 Engine.enqueueStmtNode(N, getCurrBlock(), currStmtIdx);
1144}
1145
1147 ExplodedNode *Pred) {
1148 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1149 S->getBeginLoc(),
1150 "Error evaluating end of a lifetime");
1151 LifetimeEnd PP(S, D, Pred->getStackFrame());
1152 ExplodedNode *Src = Engine.makeNode(PP, Pred->getState(), Pred);
1153
1154 ExplodedNodeSet Dst;
1155 getCheckerManager().runCheckersForLifetimeEnd(Dst, Src, D, *this);
1156 Engine.enqueueStmtNodes(Dst, currBldrCtx->getBlock(), currStmtIdx);
1157}
1158
1160 ExplodedNode *Pred) {
1161 const CXXCtorInitializer *BMI = CFGInit.getInitializer();
1162 const Expr *Init = BMI->getInit()->IgnoreImplicit();
1163 const StackFrame *SF = Pred->getStackFrame();
1164
1165 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1166 BMI->getSourceLocation(),
1167 "Error evaluating initializer");
1168
1169 // We don't clean up dead bindings here.
1170 const auto *decl = cast<CXXConstructorDecl>(SF->getDecl());
1171
1172 ProgramStateRef State = Pred->getState();
1173 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, SF));
1174
1175 ExplodedNodeSet Tmp;
1176 SVal FieldLoc;
1177
1178 // Evaluate the initializer, if necessary
1179 if (BMI->isAnyMemberInitializer()) {
1180 // Constructors build the object directly in the field,
1181 // but non-objects must be copied in from the initializer.
1182 if (getObjectUnderConstruction(State, BMI, SF)) {
1183 // The field was directly constructed, so there is no need to bind.
1184 // But we still need to stop tracking the object under construction.
1185 State = finishObjectConstruction(State, BMI, SF);
1186 PostStore PS(Init, SF, /*Loc*/ nullptr, /*tag*/ nullptr);
1187 Tmp.insert(Engine.makeNode(PS, State, Pred));
1188 } else {
1189 const ValueDecl *Field;
1190 if (BMI->isIndirectMemberInitializer()) {
1191 Field = BMI->getIndirectMember();
1192 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
1193 } else {
1194 Field = BMI->getMember();
1195 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
1196 }
1197
1198 SVal InitVal;
1199 if (Field->getType()->isArrayType()) {
1200 // Handle arrays of trivial type. We can represent this with a
1201 // primitive load/copy from the base array region.
1202 const ArraySubscriptExpr *ASE;
1203 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
1204 Init = ASE->getBase()->IgnoreImplicit();
1205
1206 InitVal = State->getSVal(Init, SF);
1207
1208 // If we fail to get the value for some reason, use a symbolic value.
1209 if (InitVal.isUnknownOrUndef()) {
1210 SValBuilder &SVB = getSValBuilder();
1211 InitVal = SVB.conjureSymbolVal(
1212 getCFGElementRef(), SF, Field->getType(), getNumVisitedCurrent());
1213 }
1214 } else {
1215 InitVal = State->getSVal(BMI->getInit(), SF);
1216 }
1217
1218 PostInitializer PP(BMI, FieldLoc.getAsRegion(), SF);
1219 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
1220 }
1221 } else if (BMI->isBaseInitializer() && isa<InitListExpr>(Init)) {
1222 // When the base class is initialized with an initialization list and the
1223 // base class does not have a ctor, there will not be a CXXConstructExpr to
1224 // initialize the base region. Hence, we need to make the bind for it.
1226 thisVal, QualType(BMI->getBaseClass(), 0), BMI->isBaseVirtual());
1227 SVal InitVal = State->getSVal(Init, SF);
1228 evalBind(Tmp, Init, Pred, BaseLoc, InitVal, /*isInit=*/true);
1229 } else {
1230 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
1231 Tmp.insert(Pred);
1232 // We already did all the work when visiting the CXXConstructExpr.
1233 }
1234
1235 // Construct PostInitializer nodes whether the state changed or not,
1236 // so that the diagnostics don't get confused.
1237 PostInitializer PP(BMI, FieldLoc.getAsRegion(), SF);
1238
1239 ExplodedNodeSet Dst;
1240 for (ExplodedNode *Pred : Tmp)
1241 Dst.insert(Engine.makeNode(PP, Pred->getState(), Pred));
1242 // Enqueue the new nodes onto the work list.
1243 Engine.enqueueStmtNodes(Dst, getCurrBlock(), currStmtIdx);
1244}
1245
1246std::pair<ProgramStateRef, uint64_t>
1247ExprEngine::prepareStateForArrayDestruction(const ProgramStateRef State,
1248 const MemRegion *Region,
1249 const QualType &ElementTy,
1250 const StackFrame *SF,
1251 SVal *ElementCountVal) {
1252 assert(Region != nullptr && "Not-null region expected");
1253
1254 QualType Ty = ElementTy.getDesugaredType(getContext());
1255 while (const auto *NTy = dyn_cast<ArrayType>(Ty))
1256 Ty = NTy->getElementType().getDesugaredType(getContext());
1257
1258 auto ElementCount = getDynamicElementCount(State, Region, svalBuilder, Ty);
1259
1260 if (ElementCountVal)
1261 *ElementCountVal = ElementCount;
1262
1263 // Note: the destructors are called in reverse order.
1264 unsigned Idx = 0;
1265 if (auto OptionalIdx = getPendingArrayDestruction(State, SF)) {
1266 Idx = *OptionalIdx;
1267 } else {
1268 // The element count is either unknown, or an SVal that's not an integer.
1269 if (!ElementCount.isConstant())
1270 return {State, 0};
1271
1272 Idx = ElementCount.getAsInteger()->getLimitedValue();
1273 }
1274
1275 if (Idx == 0)
1276 return {State, 0};
1277
1278 --Idx;
1279
1280 return {setPendingArrayDestruction(State, SF, Idx), Idx};
1281}
1282
1284 ExplodedNode *Pred) {
1285 ExplodedNodeSet Dst;
1286 switch (D.getKind()) {
1289 break;
1291 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
1292 break;
1294 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
1295 break;
1298 break;
1300 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
1301 break;
1302 default:
1303 llvm_unreachable("Unexpected dtor kind.");
1304 }
1305
1306 // Enqueue the new nodes onto the work list.
1307 Engine.enqueueStmtNodes(Dst, getCurrBlock(), currStmtIdx);
1308}
1309
1311 ExplodedNode *Pred) {
1312 ExplodedNodeSet Dst;
1314 AnalyzerOptions &Opts = AMgr.options;
1315 // TODO: We're not evaluating allocators for all cases just yet as
1316 // we're not handling the return value correctly, which causes false
1317 // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
1318 if (Opts.MayInlineCXXAllocator)
1319 VisitCXXNewAllocatorCall(NE, Pred, Dst);
1320 else {
1321 const StackFrame *SF = Pred->getStackFrame();
1322 PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), SF,
1324 Dst.insert(Engine.makeNode(PP, Pred->getState(), Pred));
1325 }
1326 Engine.enqueueStmtNodes(Dst, getCurrBlock(), currStmtIdx);
1327}
1328
1330 ExplodedNode *Pred,
1331 ExplodedNodeSet &Dst) {
1332 const auto *DtorDecl = Dtor.getDestructorDecl(getContext());
1333 const VarDecl *varDecl = Dtor.getVarDecl();
1334 QualType varType = varDecl->getType();
1335
1336 ProgramStateRef state = Pred->getState();
1337 const StackFrame *SF = Pred->getStackFrame();
1338
1339 SVal dest = state->getLValue(varDecl, SF);
1340 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
1341
1342 if (varType->isReferenceType()) {
1343 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
1344 if (!ValueRegion) {
1345 // FIXME: This should not happen. The language guarantees a presence
1346 // of a valid initializer here, so the reference shall not be undefined.
1347 // It seems that we're calling destructors over variables that
1348 // were not initialized yet.
1349 return;
1350 }
1351 Region = ValueRegion->getBaseRegion();
1352 varType = cast<TypedValueRegion>(Region)->getValueType();
1353 }
1354
1355 unsigned Idx = 0;
1356 if (isa<ArrayType>(varType)) {
1357 SVal ElementCount;
1358 std::tie(state, Idx) = prepareStateForArrayDestruction(
1359 state, Region, varType, SF, &ElementCount);
1360
1361 if (ElementCount.isConstant()) {
1362 uint64_t ArrayLength = ElementCount.getAsInteger()->getLimitedValue();
1363 assert(ArrayLength &&
1364 "An automatic dtor for a 0 length array shouldn't be triggered!");
1365
1366 // Still handle this case if we don't have assertions enabled.
1367 if (!ArrayLength) {
1368 static SimpleProgramPointTag PT(
1369 "ExprEngine", "Skipping automatic 0 length array destruction, "
1370 "which shouldn't be in the CFG.");
1371 PostImplicitCall PP(DtorDecl, varDecl->getLocation(), SF,
1372 getCFGElementRef(), &PT);
1373 Engine.makeNode(PP, Pred->getState(), Pred, /*MarkAsSink=*/true);
1374 return;
1375 }
1376 }
1377 }
1378
1379 EvalCallOptions CallOpts;
1380 Region = makeElementRegion(state, loc::MemRegionVal(Region), varType,
1381 CallOpts.IsArrayCtorOrDtor, Idx)
1382 .getAsRegion();
1383
1384 static SimpleProgramPointTag PT("ExprEngine",
1385 "Prepare for object destruction");
1386 PreImplicitCall PP(DtorDecl, varDecl->getLocation(), SF, getCFGElementRef(),
1387 &PT);
1388 Pred = Engine.makeNode(PP, state, Pred);
1389
1390 if (!Pred)
1391 return;
1392
1393 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(),
1394 /*IsBase=*/false, Pred, Dst, CallOpts);
1395}
1396
1398 ExplodedNode *Pred,
1399 ExplodedNodeSet &Dst) {
1400 ProgramStateRef State = Pred->getState();
1401 const StackFrame *SF = Pred->getStackFrame();
1402 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
1403 const Expr *Arg = DE->getArgument();
1404 QualType DTy = DE->getDestroyedType();
1405 SVal ArgVal = State->getSVal(Arg, SF);
1406
1407 // If the argument to delete is known to be a null value,
1408 // don't run destructor.
1409 if (State->isNull(ArgVal).isConstrainedTrue()) {
1411 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
1412 const CXXDestructorDecl *Dtor = RD->getDestructor();
1413
1414 PostImplicitCall PP(Dtor, DE->getBeginLoc(), SF, getCFGElementRef());
1415 Dst.insert(Engine.makeNode(PP, Pred->getState(), Pred));
1416 return;
1417 }
1418
1419 auto getDtorDecl = [](const QualType &DTy) {
1420 const CXXRecordDecl *RD = DTy->getAsCXXRecordDecl();
1421 return RD->getDestructor();
1422 };
1423
1424 unsigned Idx = 0;
1425 EvalCallOptions CallOpts;
1426 const MemRegion *ArgR = ArgVal.getAsRegion();
1427
1428 if (DE->isArrayForm()) {
1429 CallOpts.IsArrayCtorOrDtor = true;
1430 // Yes, it may even be a multi-dimensional array.
1431 while (const auto *AT = getContext().getAsArrayType(DTy))
1432 DTy = AT->getElementType();
1433
1434 if (ArgR) {
1435 SVal ElementCount;
1436 std::tie(State, Idx) =
1437 prepareStateForArrayDestruction(State, ArgR, DTy, SF, &ElementCount);
1438
1439 // If we're about to destruct a 0 length array, don't run any of the
1440 // destructors.
1441 if (ElementCount.isConstant() &&
1442 ElementCount.getAsInteger()->getLimitedValue() == 0) {
1443
1444 static SimpleProgramPointTag PT(
1445 "ExprEngine", "Skipping 0 length array delete destruction");
1446 PostImplicitCall PP(getDtorDecl(DTy), DE->getBeginLoc(), SF,
1447 getCFGElementRef(), &PT);
1448 Dst.insert(Engine.makeNode(PP, Pred->getState(), Pred));
1449 return;
1450 }
1451
1452 ArgR = State->getLValue(DTy, svalBuilder.makeArrayIndex(Idx), ArgVal)
1453 .getAsRegion();
1454 }
1455 }
1456
1457 static SimpleProgramPointTag PT("ExprEngine",
1458 "Prepare for object destruction");
1459 PreImplicitCall PP(getDtorDecl(DTy), DE->getBeginLoc(), SF,
1460 getCFGElementRef(), &PT);
1461 Pred = Engine.makeNode(PP, State, Pred);
1462
1463 if (!Pred)
1464 return;
1465
1466 VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
1467}
1468
1470 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1471 const StackFrame *SF = Pred->getStackFrame();
1472
1473 const auto *CurDtor = cast<CXXDestructorDecl>(SF->getDecl());
1474 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor, SF);
1475 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
1476
1477 // Create the base object region.
1479 QualType BaseTy = Base->getType();
1480 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
1481 Base->isVirtual());
1482
1483 EvalCallOptions CallOpts;
1484 VisitCXXDestructor(BaseTy, BaseVal.getAsRegion(), CurDtor->getBody(),
1485 /*IsBase=*/true, Pred, Dst, CallOpts);
1486}
1487
1489 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
1490 const auto *DtorDecl = D.getDestructorDecl(getContext());
1491 const FieldDecl *Member = D.getFieldDecl();
1492 QualType T = Member->getType();
1493 ProgramStateRef State = Pred->getState();
1494 const StackFrame *SF = Pred->getStackFrame();
1495
1496 const auto *CurDtor = cast<CXXDestructorDecl>(SF->getDecl());
1497 Loc ThisStorageLoc = getSValBuilder().getCXXThis(CurDtor, SF);
1498 Loc ThisLoc = State->getSVal(ThisStorageLoc).castAs<Loc>();
1499 SVal FieldVal = State->getLValue(Member, ThisLoc);
1500
1501 unsigned Idx = 0;
1502 if (isa<ArrayType>(T)) {
1503 SVal ElementCount;
1504 std::tie(State, Idx) = prepareStateForArrayDestruction(
1505 State, FieldVal.getAsRegion(), T, SF, &ElementCount);
1506
1507 if (ElementCount.isConstant()) {
1508 uint64_t ArrayLength = ElementCount.getAsInteger()->getLimitedValue();
1509 assert(ArrayLength &&
1510 "A member dtor for a 0 length array shouldn't be triggered!");
1511
1512 // Still handle this case if we don't have assertions enabled.
1513 if (!ArrayLength) {
1514 static SimpleProgramPointTag PT(
1515 "ExprEngine", "Skipping member 0 length array destruction, which "
1516 "shouldn't be in the CFG.");
1517 PostImplicitCall PP(DtorDecl, Member->getLocation(), SF,
1518 getCFGElementRef(), &PT);
1519 Engine.makeNode(PP, Pred->getState(), Pred, /*MarkAsSink=*/true);
1520 return;
1521 }
1522 }
1523 }
1524
1525 EvalCallOptions CallOpts;
1526 FieldVal =
1527 makeElementRegion(State, FieldVal, T, CallOpts.IsArrayCtorOrDtor, Idx);
1528
1529 static SimpleProgramPointTag PT("ExprEngine",
1530 "Prepare for object destruction");
1531 PreImplicitCall PP(DtorDecl, Member->getLocation(), SF, getCFGElementRef(),
1532 &PT);
1533 Pred = Engine.makeNode(PP, State, Pred);
1534
1535 if (!Pred)
1536 return;
1537
1538 VisitCXXDestructor(T, FieldVal.getAsRegion(), CurDtor->getBody(),
1539 /*IsBase=*/false, Pred, Dst, CallOpts);
1540}
1541
1543 ExplodedNode *Pred,
1544 ExplodedNodeSet &Dst) {
1546 ProgramStateRef State = Pred->getState();
1547 const StackFrame *SF = Pred->getStackFrame();
1548 const MemRegion *MR = nullptr;
1549
1550 if (std::optional<SVal> V = getObjectUnderConstruction(State, BTE, SF)) {
1551 // FIXME: Currently we insert temporary destructors for default parameters,
1552 // but we don't insert the constructors, so the entry in
1553 // ObjectsUnderConstruction may be missing.
1554 State = finishObjectConstruction(State, BTE, SF);
1555 MR = V->getAsRegion();
1556 }
1557
1558 // If copy elision has occurred, and the constructor corresponding to the
1559 // destructor was elided, we need to skip the destructor as well.
1560 if (isDestructorElided(State, BTE, SF)) {
1561 State = cleanupElidedDestructor(State, BTE, SF);
1563 SF, getCFGElementRef());
1564 Dst.insert(Engine.makeNode(PP, State, Pred));
1565 return;
1566 }
1567
1568 ExplodedNode *CleanPred = Engine.makePostStmtNode(BTE, State, Pred);
1569 if (!CleanPred || CleanPred->isSink()) {
1570 // FIXME: We can get a null node here due to temporaries being
1571 // bound to default parameters.
1572 // Sink check is just PosteriorlyOverconstrained paranoia.
1573 CleanPred = Pred;
1574 }
1575
1576 QualType T = BTE->getSubExpr()->getType();
1577
1578 EvalCallOptions CallOpts;
1579 CallOpts.IsTemporaryCtorOrDtor = true;
1580 if (!MR) {
1581 // FIXME: If we have no MR, we still need to unwrap the array to avoid
1582 // destroying the whole array at once.
1583 //
1584 // For this case there is no universal solution as there is no way to
1585 // directly create an array of temporary objects. There are some expressions
1586 // however which can create temporary objects and have an array type.
1587 //
1588 // E.g.: std::initializer_list<S>{S(), S()};
1589 //
1590 // The expression above has a type of 'const struct S[2]' but it's a single
1591 // 'std::initializer_list<>'. The destructors of the 2 temporary 'S()'
1592 // objects will be called anyway, because they are 2 separate objects in 2
1593 // separate clusters, i.e.: not an array.
1594 //
1595 // Now the 'std::initializer_list<>' is not an array either even though it
1596 // has the type of an array. The point is, we only want to invoke the
1597 // destructor for the initializer list once not twice or so.
1598 while (const ArrayType *AT = getContext().getAsArrayType(T)) {
1599 T = AT->getElementType();
1600
1601 // FIXME: Enable this flag once we handle this case properly.
1602 // CallOpts.IsArrayCtorOrDtor = true;
1603 }
1604 } else {
1605 // FIXME: We'd eventually need to makeElementRegion() trick here,
1606 // but for now we don't have the respective construction contexts,
1607 // so MR would always be null in this case. Do nothing for now.
1608 }
1609 VisitCXXDestructor(T, MR, BTE,
1610 /*IsBase=*/false, CleanPred, Dst, CallOpts);
1611}
1612
1614 ExplodedNode *Pred,
1615 ExplodedNodeSet &Dst,
1616 const CFGBlock *DstT,
1617 const CFGBlock *DstF) {
1618 ProgramStateRef State = Pred->getState();
1619 const StackFrame *SF = Pred->getStackFrame();
1620
1621 std::optional<SVal> Obj = getObjectUnderConstruction(State, BTE, SF);
1622 if (const CFGBlock *DstBlock = Obj ? DstT : DstF) {
1623 BlockEdge BE(getCurrBlock(), DstBlock, SF);
1624 Dst.insert(Engine.makeNode(BE, State, Pred));
1625 }
1626}
1627
1629 ExplodedNodeSet &PreVisit,
1630 ExplodedNodeSet &Dst) {
1631 // This is a fallback solution in case we didn't have a construction
1632 // context when we were constructing the temporary. Otherwise the map should
1633 // have been populated there.
1634 if (!getAnalysisManager().options.ShouldIncludeTemporaryDtorsInCFG) {
1635 // In case we don't have temporary destructors in the CFG, do not mark
1636 // the initialization - we would otherwise never clean it up.
1637 Dst = PreVisit;
1638 return;
1639 }
1640 for (ExplodedNode *Node : PreVisit) {
1641 ProgramStateRef State = Node->getState();
1642 const StackFrame *SF = Node->getStackFrame();
1643 if (!getObjectUnderConstruction(State, BTE, SF)) {
1644 // FIXME: Currently the state might also already contain the marker due to
1645 // incorrect handling of temporaries bound to default parameters; for
1646 // those, we currently skip the CXXBindTemporaryExpr but rely on adding
1647 // temporary destructor nodes.
1648 State = addObjectUnderConstruction(State, BTE, SF, UnknownVal());
1649 }
1650 Dst.insert(Engine.makePostStmtNode(BTE, State, Node));
1651 }
1652}
1653
1655 ArrayRef<SVal> Vs,
1657 const CallEvent *Call) const {
1658 class CollectReachableSymbolsCallback final : public SymbolVisitor {
1659 InvalidatedSymbols &Symbols;
1660
1661 public:
1662 explicit CollectReachableSymbolsCallback(InvalidatedSymbols &Symbols)
1663 : Symbols(Symbols) {}
1664
1665 const InvalidatedSymbols &getSymbols() const { return Symbols; }
1666
1667 bool VisitSymbol(SymbolRef Sym) override {
1668 Symbols.insert(Sym);
1669 return true;
1670 }
1671 };
1672 InvalidatedSymbols Symbols;
1673 CollectReachableSymbolsCallback CallBack(Symbols);
1674 for (SVal V : Vs)
1675 State->scanReachableSymbols(V, CallBack);
1676
1678 State, CallBack.getSymbols(), Call, K, nullptr);
1679}
1680
1682 ExplodedNodeSet &Dst) {
1683 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1684 S->getBeginLoc(), "Error evaluating statement");
1685
1686 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
1687
1688 switch (S->getStmtClass()) {
1689 // C++, OpenMP and ARC stuff we don't support yet.
1690 case Stmt::CXXDependentScopeMemberExprClass:
1691 case Stmt::CXXReflectExprClass:
1692 case Stmt::CXXTryStmtClass:
1693 case Stmt::CXXTypeidExprClass:
1694 case Stmt::CXXUuidofExprClass:
1695 case Stmt::CXXFoldExprClass:
1696 case Stmt::MSPropertyRefExprClass:
1697 case Stmt::MSPropertySubscriptExprClass:
1698 case Stmt::CXXUnresolvedConstructExprClass:
1699 case Stmt::DependentScopeDeclRefExprClass:
1700 case Stmt::ArrayTypeTraitExprClass:
1701 case Stmt::ExpressionTraitExprClass:
1702 case Stmt::UnresolvedLookupExprClass:
1703 case Stmt::UnresolvedMemberExprClass:
1704 case Stmt::RecoveryExprClass:
1705 case Stmt::CXXNoexceptExprClass:
1706 case Stmt::PackExpansionExprClass:
1707 case Stmt::PackIndexingExprClass:
1708 case Stmt::SubstNonTypeTemplateParmPackExprClass:
1709 case Stmt::FunctionParmPackExprClass:
1710 case Stmt::CoroutineBodyStmtClass:
1711 case Stmt::CoawaitExprClass:
1712 case Stmt::DependentCoawaitExprClass:
1713 case Stmt::CoreturnStmtClass:
1714 case Stmt::CoyieldExprClass:
1715 case Stmt::SEHTryStmtClass:
1716 case Stmt::SEHExceptStmtClass:
1717 case Stmt::SEHLeaveStmtClass:
1718 case Stmt::SEHFinallyStmtClass:
1719 case Stmt::CXXExpansionStmtPatternClass:
1720 case Stmt::CXXExpansionStmtInstantiationClass:
1721 case Stmt::CXXExpansionSelectExprClass:
1722 case Stmt::OMPCanonicalLoopClass:
1723 case Stmt::OMPParallelDirectiveClass:
1724 case Stmt::OMPSimdDirectiveClass:
1725 case Stmt::OMPForDirectiveClass:
1726 case Stmt::OMPForSimdDirectiveClass:
1727 case Stmt::OMPSectionsDirectiveClass:
1728 case Stmt::OMPSectionDirectiveClass:
1729 case Stmt::OMPScopeDirectiveClass:
1730 case Stmt::OMPSingleDirectiveClass:
1731 case Stmt::OMPMasterDirectiveClass:
1732 case Stmt::OMPCriticalDirectiveClass:
1733 case Stmt::OMPParallelForDirectiveClass:
1734 case Stmt::OMPParallelForSimdDirectiveClass:
1735 case Stmt::OMPParallelSectionsDirectiveClass:
1736 case Stmt::OMPParallelMasterDirectiveClass:
1737 case Stmt::OMPParallelMaskedDirectiveClass:
1738 case Stmt::OMPTaskDirectiveClass:
1739 case Stmt::OMPTaskyieldDirectiveClass:
1740 case Stmt::OMPBarrierDirectiveClass:
1741 case Stmt::OMPTaskwaitDirectiveClass:
1742 case Stmt::OMPErrorDirectiveClass:
1743 case Stmt::OMPTaskgroupDirectiveClass:
1744 case Stmt::OMPFlushDirectiveClass:
1745 case Stmt::OMPDepobjDirectiveClass:
1746 case Stmt::OMPScanDirectiveClass:
1747 case Stmt::OMPOrderedStandaloneDirectiveClass:
1748 case Stmt::OMPOrderedBlockAssocDirectiveClass:
1749 case Stmt::OMPAtomicDirectiveClass:
1750 case Stmt::OMPAssumeDirectiveClass:
1751 case Stmt::OMPTargetDirectiveClass:
1752 case Stmt::OMPTargetDataDirectiveClass:
1753 case Stmt::OMPTargetEnterDataDirectiveClass:
1754 case Stmt::OMPTargetExitDataDirectiveClass:
1755 case Stmt::OMPTargetParallelDirectiveClass:
1756 case Stmt::OMPTargetParallelForDirectiveClass:
1757 case Stmt::OMPTargetUpdateDirectiveClass:
1758 case Stmt::OMPTeamsDirectiveClass:
1759 case Stmt::OMPCancellationPointDirectiveClass:
1760 case Stmt::OMPCancelDirectiveClass:
1761 case Stmt::OMPTaskLoopDirectiveClass:
1762 case Stmt::OMPTaskLoopSimdDirectiveClass:
1763 case Stmt::OMPMasterTaskLoopDirectiveClass:
1764 case Stmt::OMPMaskedTaskLoopDirectiveClass:
1765 case Stmt::OMPMasterTaskLoopSimdDirectiveClass:
1766 case Stmt::OMPMaskedTaskLoopSimdDirectiveClass:
1767 case Stmt::OMPParallelMasterTaskLoopDirectiveClass:
1768 case Stmt::OMPParallelMaskedTaskLoopDirectiveClass:
1769 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass:
1770 case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass:
1771 case Stmt::OMPDistributeDirectiveClass:
1772 case Stmt::OMPDistributeParallelForDirectiveClass:
1773 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1774 case Stmt::OMPDistributeSimdDirectiveClass:
1775 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1776 case Stmt::OMPTargetSimdDirectiveClass:
1777 case Stmt::OMPTeamsDistributeDirectiveClass:
1778 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1779 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1780 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1781 case Stmt::OMPTargetTeamsDirectiveClass:
1782 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1783 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1784 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1785 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1786 case Stmt::OMPReverseDirectiveClass:
1787 case Stmt::OMPStripeDirectiveClass:
1788 case Stmt::OMPTileDirectiveClass:
1789 case Stmt::OMPInterchangeDirectiveClass:
1790 case Stmt::OMPSplitDirectiveClass:
1791 case Stmt::OMPFuseDirectiveClass:
1792 case Stmt::OMPInteropDirectiveClass:
1793 case Stmt::OMPDispatchDirectiveClass:
1794 case Stmt::OMPMaskedDirectiveClass:
1795 case Stmt::OMPGenericLoopDirectiveClass:
1796 case Stmt::OMPTeamsGenericLoopDirectiveClass:
1797 case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
1798 case Stmt::OMPParallelGenericLoopDirectiveClass:
1799 case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
1800 case Stmt::CapturedStmtClass:
1801 case Stmt::SYCLKernelCallStmtClass:
1802 case Stmt::UnresolvedSYCLKernelCallStmtClass:
1803 case Stmt::OpenACCComputeConstructClass:
1804 case Stmt::OpenACCLoopConstructClass:
1805 case Stmt::OpenACCCombinedConstructClass:
1806 case Stmt::OpenACCDataConstructClass:
1807 case Stmt::OpenACCEnterDataConstructClass:
1808 case Stmt::OpenACCExitDataConstructClass:
1809 case Stmt::OpenACCHostDataConstructClass:
1810 case Stmt::OpenACCWaitConstructClass:
1811 case Stmt::OpenACCCacheConstructClass:
1812 case Stmt::OpenACCInitConstructClass:
1813 case Stmt::OpenACCShutdownConstructClass:
1814 case Stmt::OpenACCSetConstructClass:
1815 case Stmt::OpenACCUpdateConstructClass:
1816 case Stmt::OpenACCAtomicConstructClass:
1817 case Stmt::OMPUnrollDirectiveClass:
1818 case Stmt::OMPMetaDirectiveClass:
1819 case Stmt::HLSLOutArgExprClass: {
1820 const ExplodedNode *Node = Engine.makePostStmtNode(
1821 S, Pred->getState(), Pred, /*MarkAsSink=*/true);
1822 Engine.addAbortedBlock(Node, getCurrBlock());
1823 break;
1824 }
1825
1826 case Stmt::ParenExprClass:
1827 llvm_unreachable("ParenExprs already handled.");
1828 case Stmt::GenericSelectionExprClass:
1829 llvm_unreachable("GenericSelectionExprs already handled.");
1830 // Cases that should never be evaluated simply because they shouldn't
1831 // appear in the CFG.
1832 case Stmt::BreakStmtClass:
1833 case Stmt::CaseStmtClass:
1834 case Stmt::CompoundStmtClass:
1835 case Stmt::ContinueStmtClass:
1836 case Stmt::CXXForRangeStmtClass:
1837 case Stmt::DefaultStmtClass:
1838 case Stmt::DoStmtClass:
1839 case Stmt::ForStmtClass:
1840 case Stmt::GotoStmtClass:
1841 case Stmt::IfStmtClass:
1842 case Stmt::IndirectGotoStmtClass:
1843 case Stmt::LabelStmtClass:
1844 case Stmt::NoStmtClass:
1845 case Stmt::NullStmtClass:
1846 case Stmt::SwitchStmtClass:
1847 case Stmt::WhileStmtClass:
1848 case Stmt::DeferStmtClass:
1849 case Expr::MSDependentExistsStmtClass:
1850 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
1851 case Stmt::ImplicitValueInitExprClass:
1852 // These nodes are shared in the CFG and would case caching out.
1853 // Moreover, no additional evaluation required for them, the
1854 // analyzer can reconstruct these values from the AST.
1855 llvm_unreachable("Should be pruned from CFG");
1856
1857 case Stmt::ObjCSubscriptRefExprClass:
1858 case Stmt::ObjCPropertyRefExprClass:
1859 llvm_unreachable("These are handled by PseudoObjectExpr");
1860
1861 case Stmt::GNUNullExprClass: {
1862 // GNU __null is a pointer-width integer, not an actual pointer.
1863 SVal Val = svalBuilder.makeIntValWithWidth(getContext().VoidPtrTy, 0);
1864 Dst.insert(Engine.makeNodeWithBinding(Pred, cast<Expr>(S), Val));
1865 break;
1866 }
1867
1868 case Stmt::ObjCAtSynchronizedStmtClass:
1870 break;
1871
1872 case Expr::ConstantExprClass:
1873 case Stmt::ExprWithCleanupsClass:
1874 Dst.insert(Pred);
1875 // Handled due to fully linearised CFG.
1876 break;
1877
1878 case Stmt::CXXBindTemporaryExprClass: {
1879 ExplodedNodeSet PreVisit;
1880 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1884 break;
1885 }
1886
1887 case Stmt::ArrayInitLoopExprClass:
1889 break;
1890 // Cases not handled yet; but will handle some day.
1891 case Stmt::DesignatedInitExprClass:
1892 case Stmt::DesignatedInitUpdateExprClass:
1893 case Stmt::ArrayInitIndexExprClass:
1894 case Stmt::ExtVectorElementExprClass:
1895 case Stmt::MatrixElementExprClass:
1896 case Stmt::ImaginaryLiteralClass:
1897 case Stmt::ObjCAtCatchStmtClass:
1898 case Stmt::ObjCAtFinallyStmtClass:
1899 case Stmt::ObjCAtTryStmtClass:
1900 case Stmt::ObjCAutoreleasePoolStmtClass:
1901 case Stmt::ObjCEncodeExprClass:
1902 case Stmt::ObjCIsaExprClass:
1903 case Stmt::ObjCProtocolExprClass:
1904 case Stmt::ObjCSelectorExprClass:
1905 case Stmt::ParenListExprClass:
1906 case Stmt::ShuffleVectorExprClass:
1907 case Stmt::ConvertVectorExprClass:
1908 case Stmt::VAArgExprClass:
1909 case Stmt::CUDAKernelCallExprClass:
1910 case Stmt::OpaqueValueExprClass:
1911 case Stmt::AsTypeExprClass:
1912 case Stmt::ConceptSpecializationExprClass:
1913 case Stmt::CXXRewrittenBinaryOperatorClass:
1914 case Stmt::RequiresExprClass:
1915 case Stmt::EmbedExprClass:
1916 // Fall through.
1917
1918 // Cases we intentionally don't evaluate, since they don't need
1919 // to be explicitly evaluated.
1920 case Stmt::PredefinedExprClass:
1921 case Stmt::AddrLabelExprClass:
1922 case Stmt::IntegerLiteralClass:
1923 case Stmt::FixedPointLiteralClass:
1924 case Stmt::CharacterLiteralClass:
1925 case Stmt::CXXScalarValueInitExprClass:
1926 case Stmt::CXXBoolLiteralExprClass:
1927 case Stmt::ObjCBoolLiteralExprClass:
1928 case Stmt::ObjCAvailabilityCheckExprClass:
1929 case Stmt::FloatingLiteralClass:
1930 case Stmt::NoInitExprClass:
1931 case Stmt::SizeOfPackExprClass:
1932 case Stmt::StringLiteralClass:
1933 case Stmt::SourceLocExprClass:
1934 case Stmt::ObjCStringLiteralClass:
1935 case Stmt::CXXPseudoDestructorExprClass:
1936 case Stmt::SubstNonTypeTemplateParmExprClass:
1937 case Stmt::CXXNullPtrLiteralExprClass:
1938 case Stmt::ArraySectionExprClass:
1939 case Stmt::OMPArrayShapingExprClass:
1940 case Stmt::OMPIteratorExprClass:
1941 case Stmt::SYCLUniqueStableNameExprClass:
1942 case Stmt::OpenACCAsteriskSizeExprClass:
1943 case Stmt::TypeTraitExprClass: {
1944 ExplodedNodeSet preVisit;
1945 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1946 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1947 break;
1948 }
1949
1950 case Stmt::AttributedStmtClass: {
1952 break;
1953 }
1954
1955 case Stmt::CXXDefaultArgExprClass:
1956 case Stmt::CXXDefaultInitExprClass: {
1957 ExplodedNodeSet PreVisit;
1958 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1959
1960 ExplodedNodeSet Tmp;
1961
1962 const Expr *ArgE;
1963 if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1964 ArgE = DefE->getExpr();
1965 else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1966 ArgE = DefE->getExpr();
1967 else
1968 llvm_unreachable("unknown constant wrapper kind");
1969
1970 bool IsTemporary = false;
1971 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1972 ArgE = MTE->getSubExpr();
1973 IsTemporary = true;
1974 }
1975
1976 std::optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1977 if (!ConstantVal)
1978 ConstantVal = UnknownVal();
1979
1980 const StackFrame *SF = Pred->getStackFrame();
1981 for (const auto I : PreVisit) {
1982 ProgramStateRef State = I->getState();
1983 State = State->BindExpr(cast<Expr>(S), SF, *ConstantVal);
1984 if (IsTemporary)
1985 State = createTemporaryRegionIfNeeded(State, SF, cast<Expr>(S),
1986 cast<Expr>(S));
1987 Tmp.insert(Engine.makePostStmtNode(S, State, I));
1988 }
1989
1990 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1991 break;
1992 }
1993
1994 // Cases we evaluate as opaque expressions, conjuring a symbol.
1995 case Stmt::CXXStdInitializerListExprClass:
1996 case Expr::ObjCArrayLiteralClass:
1997 case Expr::ObjCDictionaryLiteralClass:
1998 case Expr::ObjCBoxedExprClass: {
1999 ExplodedNodeSet preVisit;
2000 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
2001
2002 ExplodedNodeSet Tmp;
2003
2004 const auto *Ex = cast<Expr>(S);
2005 QualType resultType = Ex->getType();
2006
2007 for (const auto N : preVisit) {
2008 const StackFrame *SF = N->getStackFrame();
2009 SVal result = svalBuilder.conjureSymbolVal(
2010 /*symbolTag=*/nullptr, getCFGElementRef(), SF, resultType,
2012 ProgramStateRef State = N->getState()->BindExpr(Ex, SF, result);
2013
2014 // Escape pointers passed into the list, unless it's an ObjC boxed
2015 // expression which is not a boxable C structure.
2016 if (!(isa<ObjCBoxedExpr>(Ex) &&
2017 !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
2018 ->getType()->isRecordType()))
2019 for (auto Child : Ex->children()) {
2020 assert(Child);
2021 const auto *ChildExpr = dyn_cast<Expr>(Child);
2022 SVal Val = ChildExpr ? State->getSVal(ChildExpr, SF) : UnknownVal();
2023 State = escapeValues(State, Val, PSK_EscapeOther);
2024 }
2025
2026 Tmp.insert(Engine.makePostStmtNode(S, State, N));
2027 }
2028
2029 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
2030 break;
2031 }
2032
2033 case Stmt::ArraySubscriptExprClass:
2035 break;
2036
2037 case Stmt::MatrixSingleSubscriptExprClass:
2038 llvm_unreachable(
2039 "Support for MatrixSingleSubscriptExprClass is not implemented.");
2040 break;
2041
2042 case Stmt::MatrixSubscriptExprClass:
2043 llvm_unreachable("Support for MatrixSubscriptExpr is not implemented.");
2044 break;
2045
2046 case Stmt::GCCAsmStmtClass: {
2047 ExplodedNodeSet PreVisit;
2048 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
2049 ExplodedNodeSet PostVisit;
2050 for (ExplodedNode *const N : PreVisit)
2051 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), N, PostVisit);
2052 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
2053 break;
2054 }
2055
2056 case Stmt::MSAsmStmtClass:
2057 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
2058 break;
2059
2060 case Stmt::BlockExprClass:
2061 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
2062 break;
2063
2064 case Stmt::LambdaExprClass:
2065 if (AMgr.options.ShouldInlineLambdas) {
2066 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
2067 } else {
2068 const ExplodedNode *Node = Engine.makePostStmtNode(
2069 S, Pred->getState(), Pred, /*MarkAsSink=*/true);
2070 Engine.addAbortedBlock(Node, getCurrBlock());
2071 }
2072 break;
2073
2074 case Stmt::BinaryOperatorClass: {
2075 const auto *B = cast<BinaryOperator>(S);
2076 if (B->isLogicalOp()) {
2077 VisitLogicalExpr(B, Pred, Dst);
2078 break;
2079 } else if (B->getOpcode() == BO_Comma) {
2080 SVal Val =
2081 Pred->getState()->getSVal(B->getRHS(), Pred->getStackFrame());
2082 Dst.insert(Engine.makeNodeWithBinding(Pred, B, Val));
2083 break;
2084 }
2085
2086 if (AMgr.options.ShouldEagerlyAssume &&
2087 (B->isRelationalOp() || B->isEqualityOp())) {
2088 ExplodedNodeSet Tmp;
2091 }
2092 else
2094
2095 break;
2096 }
2097
2098 case Stmt::CXXOperatorCallExprClass:
2099 case Stmt::CallExprClass:
2100 case Stmt::CXXMemberCallExprClass:
2101 case Stmt::UserDefinedLiteralClass:
2102 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
2103 break;
2104
2105 case Stmt::CXXCatchStmtClass:
2107 break;
2108
2109 case Stmt::CXXTemporaryObjectExprClass:
2110 case Stmt::CXXConstructExprClass:
2112 break;
2113
2114 case Stmt::CXXInheritedCtorInitExprClass:
2116 Dst);
2117 break;
2118
2119 case Stmt::CXXNewExprClass: {
2120
2121 ExplodedNodeSet PreVisit;
2122 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
2123
2124 ExplodedNodeSet PostVisit;
2125 for (const auto i : PreVisit)
2126 VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
2127
2128 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
2129 break;
2130 }
2131
2132 case Stmt::CXXDeleteExprClass: {
2133 ExplodedNodeSet PreVisit;
2134 const auto *CDE = cast<CXXDeleteExpr>(S);
2135 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
2136
2137 ExplodedNodeSet PostVisit;
2138 for (const auto i : PreVisit)
2139 VisitCXXDeleteExpr(CDE, i, PostVisit);
2140
2141 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
2142 break;
2143 }
2144 // FIXME: ChooseExpr is really a constant. We need to fix
2145 // the CFG do not model them as explicit control-flow.
2146
2147 case Stmt::ChooseExprClass: { // __builtin_choose_expr
2148 const auto *C = cast<ChooseExpr>(S);
2149 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
2150 break;
2151 }
2152
2153 case Stmt::CompoundAssignOperatorClass:
2155 break;
2156
2157 case Stmt::CompoundLiteralExprClass:
2159 break;
2160
2161 case Stmt::BinaryConditionalOperatorClass:
2162 case Stmt::ConditionalOperatorClass: { // '?' operator
2163 const auto *C = cast<AbstractConditionalOperator>(S);
2164 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
2165 break;
2166 }
2167
2168 case Stmt::CXXThisExprClass:
2169 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
2170 break;
2171
2172 case Stmt::DeclRefExprClass: {
2173 const auto *DE = cast<DeclRefExpr>(S);
2174 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
2175 break;
2176 }
2177
2178 case Stmt::DeclStmtClass:
2179 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
2180 break;
2181
2182 case Stmt::ImplicitCastExprClass:
2183 case Stmt::CStyleCastExprClass:
2184 case Stmt::CXXStaticCastExprClass:
2185 case Stmt::CXXDynamicCastExprClass:
2186 case Stmt::CXXReinterpretCastExprClass:
2187 case Stmt::CXXConstCastExprClass:
2188 case Stmt::CXXFunctionalCastExprClass:
2189 case Stmt::BuiltinBitCastExprClass:
2190 case Stmt::ObjCBridgedCastExprClass:
2191 case Stmt::CXXAddrspaceCastExprClass: {
2192 const auto *C = cast<CastExpr>(S);
2193 ExplodedNodeSet dstExpr;
2194 VisitCast(C, C->getSubExpr(), Pred, dstExpr);
2195
2196 // Handle the postvisit checks.
2197 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
2198 break;
2199 }
2200
2201 case Expr::MaterializeTemporaryExprClass: {
2202 const auto *MTE = cast<MaterializeTemporaryExpr>(S);
2203 ExplodedNodeSet dstPrevisit;
2204 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
2205 ExplodedNodeSet dstExpr;
2206 for (const auto i : dstPrevisit)
2207 CreateCXXTemporaryObject(MTE, i, dstExpr);
2208 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
2209 break;
2210 }
2211
2212 case Stmt::InitListExprClass: {
2213 const InitListExpr *E = cast<InitListExpr>(S);
2214 ConstructInitList(E, E->inits(), E->isTransparent(), Pred, Dst);
2215 break;
2216 }
2217
2218 case Expr::CXXParenListInitExprClass: {
2220 ConstructInitList(E, E->getInitExprs(), /*IsTransparent*/ false, Pred,
2221 Dst);
2222 break;
2223 }
2224
2225 case Stmt::MemberExprClass:
2226 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
2227 break;
2228
2229 case Stmt::AtomicExprClass:
2230 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
2231 break;
2232
2233 case Stmt::ObjCIvarRefExprClass:
2235 break;
2236
2237 case Stmt::ObjCForCollectionStmtClass:
2239 break;
2240
2241 case Stmt::ObjCMessageExprClass:
2243 break;
2244
2245 case Stmt::ObjCAtThrowStmtClass:
2246 case Stmt::CXXThrowExprClass:
2247 // FIXME: This is not complete. We basically treat @throw as
2248 // an abort.
2249 Engine.makePostStmtNode(S, Pred->getState(), Pred, /*MarkAsSink=*/true);
2250 break;
2251
2252 case Stmt::ReturnStmtClass:
2253 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
2254 break;
2255
2256 case Stmt::OffsetOfExprClass: {
2257 ExplodedNodeSet PreVisit;
2258 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
2259
2260 ExplodedNodeSet PostVisit;
2261 for (const auto Node : PreVisit)
2262 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
2263
2264 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
2265 break;
2266 }
2267
2268 case Stmt::UnaryExprOrTypeTraitExprClass:
2270 Dst);
2271 break;
2272
2273 case Stmt::StmtExprClass: {
2274 const auto *SE = cast<StmtExpr>(S);
2275
2276 if (SE->getSubStmt()->body_empty()) {
2277 // Empty statement expression.
2278 assert(SE->getType() == getContext().VoidTy
2279 && "Empty statement expression must have void type.");
2280 } else if (const auto *LastExpr =
2281 dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
2282 SVal Val = Pred->getState()->getSVal(LastExpr, Pred->getStackFrame());
2283 Pred = Engine.makeNodeWithBinding(Pred, SE, Val);
2284 }
2285 Dst.insert(Pred);
2286 break;
2287 }
2288
2289 case Stmt::UnaryOperatorClass: {
2290 const auto *U = cast<UnaryOperator>(S);
2291 if (AMgr.options.ShouldEagerlyAssume && (U->getOpcode() == UO_LNot)) {
2292 ExplodedNodeSet Tmp;
2293 VisitUnaryOperator(U, Pred, Tmp);
2295 }
2296 else
2297 VisitUnaryOperator(U, Pred, Dst);
2298 break;
2299 }
2300
2301 case Stmt::PseudoObjectExprClass: {
2302 const auto *PE = cast<PseudoObjectExpr>(S);
2303 SVal V = UnknownVal();
2304 if (const Expr *Result = PE->getResultExpr())
2305 V = Pred->getState()->getSVal(Result, Pred->getStackFrame());
2306 Dst.insert(Engine.makeNodeWithBinding(Pred, PE, V));
2307 break;
2308 }
2309
2310 case Expr::ObjCIndirectCopyRestoreExprClass: {
2311 // ObjCIndirectCopyRestoreExpr implies passing a temporary for
2312 // correctness of lifetime management. Due to limited analysis
2313 // of ARC, this is implemented as direct arg passing.
2314 const auto *OIE = cast<ObjCIndirectCopyRestoreExpr>(S);
2315 const Expr *E = OIE->getSubExpr();
2316 SVal V = Pred->getState()->getSVal(E, Pred->getStackFrame());
2317 Dst.insert(Engine.makeNodeWithBinding(Pred, OIE, V));
2318 break;
2319 }
2320 }
2321}
2322
2323bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
2324 const StackFrame *CalleeSF) {
2325 const StackFrame *CallerSF = CalleeSF->getParent();
2326 assert(CalleeSF && CallerSF);
2327 ExplodedNode *BeforeProcessingCall = nullptr;
2328 const Expr *CE = CalleeSF->getCallSite();
2329
2330 // Find the first node before we started processing the call expression.
2331 while (N) {
2332 ProgramPoint L = N->getLocation();
2333 BeforeProcessingCall = N;
2334 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2335
2336 // Skip the nodes corresponding to the inlined code.
2337 if (L.getStackFrame() != CallerSF)
2338 continue;
2339 // We reached the caller. Find the node right before we started
2340 // processing the call.
2341 if (L.isPurgeKind())
2342 continue;
2343 if (L.getAs<PreImplicitCall>())
2344 continue;
2345 if (L.getAs<CallEnter>())
2346 continue;
2347 if (std::optional<StmtPoint> SP = L.getAs<StmtPoint>())
2348 if (SP->getStmt() == CE)
2349 continue;
2350 break;
2351 }
2352
2353 if (!BeforeProcessingCall)
2354 return false;
2355
2356 // TODO: Clean up the unneeded nodes.
2357
2358 // Build an Epsilon node from which we will restart the analyzes.
2359 // Note that CE is permitted to be NULL!
2360 static SimpleProgramPointTag PT("ExprEngine", "Replay without inlining");
2361 ProgramPoint NewNodeLoc =
2362 EpsilonPoint(BeforeProcessingCall->getStackFrame(), CE, nullptr, &PT);
2363 // Add the special flag to GDM to signal retrying with no inlining.
2364 // Note, changing the state ensures that we are not going to cache out.
2365 // NOTE: This stores the call site (CE) in the state trait, but the the
2366 // actual pointer value is only checked by an assertion; for the analysis,
2367 // only the presence or absence of this trait matters.
2368 // TODO: If we are handling a destructor call, CE is nullpointer (because it
2369 // ultimately comes from the `Origin` of a `CXXDestructorCall`), which is
2370 // indistinguishable from the absence (default state) of this state trait.
2371 // I don't think that this bad logic causes actually observable problems, but
2372 // it would be nice to clean it up if somebody has time to do so.
2373 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
2374 NewNodeState = NewNodeState->set<ReplayWithoutInlining>(CE);
2375
2376 // Make the new node a successor of BeforeProcessingCall.
2377 bool IsNew = false;
2378 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
2379 // We cached out at this point. Caching out is common due to us backtracking
2380 // from the inlined function, which might spawn several paths.
2381 if (!IsNew)
2382 return true;
2383
2384 NewNode->addPredecessor(BeforeProcessingCall, G);
2385
2386 // Add the new node to the work list.
2387 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
2388 CalleeSF->getIndex());
2389 NumTimesRetriedWithoutInlining++;
2390 return true;
2391}
2392
2393/// Block entrance. (Update counters).
2395 ExplodedNode *Pred) {
2396 const StackFrame *SF = Pred->getStackFrame();
2397 const Stmt *Term = getCurrBlock()->getTerminatorStmt();
2398 ProgramStateRef State = Pred->getState();
2399 unsigned MaxBlockVisit = AMgr.options.maxBlockVisitOnPath;
2400
2401 // If we reach a loop which has a known bound (and meets other constraints)
2402 // then consider completely unrolling it.
2403 if (AMgr.options.ShouldUnrollLoops) {
2404 if (Term)
2405 State = updateLoopStack(Term, AMgr.getASTContext(), Pred, MaxBlockVisit);
2406 // Is we are inside an unrolled loop then no need the check the counters.
2407 if (isUnrolledState(State))
2408 return Engine.makeNode(BE, State, Pred);
2409 }
2410
2411 // If this block is terminated by a loop and it has already been visited the
2412 // maximum number of times, widen the loop.
2413 unsigned int BlockCount = getNumVisitedCurrent();
2414 if (BlockCount == MaxBlockVisit - 1 && AMgr.options.ShouldWidenLoops) {
2415 if (!isa_and_nonnull<ForStmt, WhileStmt, DoStmt, CXXForRangeStmt>(Term))
2416 return Engine.makeNode(BE, State, Pred);
2417
2418 // FIXME:
2419 // We cannot use the CFG element from the via `ExprEngine::getCFGElementRef`
2420 // since we are currently at the block entrance and the current reference
2421 // would be stale. Ideally, we should pass on the terminator of the CFG
2422 // block, but the terminator cannot be referred as a CFG element.
2423 // Here we just pass the the first CFG element in the block.
2424 ProgramStateRef WidenedState = getWidenedLoopState(
2425 State, SF, BlockCount, *getCurrBlock()->ref_begin());
2426 return Engine.makeNode(BE, WidenedState, Pred);
2427 }
2428
2429 // If we did not reach MaxBlockVisitOnPath, continue the analysis normally.
2430 if (BlockCount < MaxBlockVisit)
2431 return Engine.makeNode(BE, State, Pred);
2432
2433 // ... otherwise, discard this execution path.
2434 static SimpleProgramPointTag Tag(TagProviderName, "Block count exceeded");
2435 const ExplodedNode *Sink =
2436 Engine.makeNode(BE.withTag(&Tag), State, Pred, /*MarkAsSink=*/true);
2437
2438 if (!SF->inTopFrame()) {
2439 // FIXME: This will unconditionally prevent inlining this function (even
2440 // from other entry points), which is not a reasonable heuristic: even if
2441 // we reached max block count on this particular execution path, there
2442 // may be other execution paths (especially with other parametrizations)
2443 // where the analyzer can reach the end of the function (so there is no
2444 // natural reason to avoid inlining it). However, disabling this would
2445 // significantly increase the analysis time (because more entry points
2446 // would exhaust their allocated budget), so it must be compensated by a
2447 // different (more reasonable) reduction of analysis scope.
2448 Engine.FunctionSummaries->markShouldNotInline(SF->getDecl());
2449
2450 // Re-run the call evaluation without inlining it, by storing the
2451 // no-inlining policy in the state and enqueuing the new work item on
2452 // the list. Replay should almost never fail. Use the stats to catch it
2453 // if it does.
2454 if (!AMgr.options.NoRetryExhausted && replayWithoutInlining(Pred, SF))
2455 return nullptr;
2456 NumMaxBlockCountReachedInInlined++;
2457 } else
2458 NumMaxBlockCountReached++;
2459
2460 // Make sink nodes as exhausted(for stats) only if retry failed.
2461 Engine.blocksExhausted.push_back(std::make_pair(BE, Sink));
2462
2463 return nullptr;
2464}
2465
2467 ExplodedNode *Pred,
2468 ExplodedNodeSet &Dst) {
2469 llvm::PrettyStackTraceFormat CrashInfo(
2470 "Processing block entrance B%d -> B%d",
2471 Entrance.getPreviousBlock()->getBlockID(),
2472 Entrance.getBlock()->getBlockID());
2473 getCheckerManager().runCheckersForBlockEntrance(Dst, Pred, Entrance, *this);
2474}
2475
2476//===----------------------------------------------------------------------===//
2477// Branch processing.
2478//===----------------------------------------------------------------------===//
2479
2480/// RecoverCastedSymbol - A helper function for ProcessBranch that is used
2481/// to try to recover some path-sensitivity for casts of symbolic
2482/// integers that promote their values (which are currently not tracked well).
2483/// This function returns the SVal bound to Condition->IgnoreCasts if all the
2484// cast(s) did was sign-extend the original value.
2486 const StackFrame *SF, ASTContext &Ctx) {
2487
2488 const auto *Ex = dyn_cast<Expr>(Condition);
2489 if (!Ex)
2490 return UnknownVal();
2491
2492 uint64_t bits = 0;
2493 bool bitsInit = false;
2494
2495 while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
2496 QualType T = CE->getType();
2497
2498 if (!T->isIntegralOrEnumerationType())
2499 return UnknownVal();
2500
2501 uint64_t newBits = Ctx.getTypeSize(T);
2502 if (!bitsInit || newBits < bits) {
2503 bitsInit = true;
2504 bits = newBits;
2505 }
2506
2507 Ex = CE->getSubExpr();
2508 }
2509
2510 // We reached a non-cast. Is it a symbolic value?
2511 QualType T = Ex->getType();
2512
2513 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
2514 Ctx.getTypeSize(T) > bits)
2515 return UnknownVal();
2516
2517 return state->getSVal(Ex, SF);
2518}
2519
2520#ifndef NDEBUG
2521static const Stmt *getRightmostLeaf(const Stmt *Condition) {
2522 while (Condition) {
2523 const auto *BO = dyn_cast<BinaryOperator>(Condition);
2524 if (!BO || !BO->isLogicalOp()) {
2525 return Condition;
2526 }
2527 Condition = BO->getRHS()->IgnoreParens();
2528 }
2529 return nullptr;
2530}
2531#endif
2532
2533// Returns the condition the branch at the end of 'B' depends on and whose value
2534// has been evaluated within 'B'.
2535// In most cases, the terminator condition of 'B' will be evaluated fully in
2536// the last statement of 'B'; in those cases, the resolved condition is the
2537// given 'Condition'.
2538// If the condition of the branch is a logical binary operator tree, the CFG is
2539// optimized: in that case, we know that the expression formed by all but the
2540// rightmost leaf of the logical binary operator tree must be true, and thus
2541// the branch condition is at this point equivalent to the truth value of that
2542// rightmost leaf; the CFG block thus only evaluates this rightmost leaf
2543// expression in its final statement. As the full condition in that case was
2544// not evaluated, and is thus not in the SVal cache, we need to use that leaf
2545// expression to evaluate the truth value of the condition in the current state
2546// space.
2548 const CFGBlock *B) {
2549 if (const auto *Ex = dyn_cast<Expr>(Condition))
2550 Condition = Ex->IgnoreParens();
2551
2552 const auto *BO = dyn_cast<BinaryOperator>(Condition);
2553 if (!BO || !BO->isLogicalOp())
2554 return Condition;
2555
2556 assert(B->getTerminator().isStmtBranch() &&
2557 "Other kinds of branches are handled separately!");
2558
2559 // For logical operations, we still have the case where some branches
2560 // use the traditional "merge" approach and others sink the branch
2561 // directly into the basic blocks representing the logical operation.
2562 // We need to distinguish between those two cases here.
2563
2564 // The invariants are still shifting, but it is possible that the
2565 // last element in a CFGBlock is not a CFGStmt. Look for the last
2566 // CFGStmt as the value of the condition.
2567 for (CFGElement Elem : llvm::reverse(*B)) {
2568 std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
2569 if (!CS)
2570 continue;
2571 const Stmt *LastStmt = CS->getStmt();
2572 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
2573 return LastStmt;
2574 }
2575 llvm_unreachable("could not resolve condition");
2576}
2577
2579 std::pair<const ObjCForCollectionStmt *, const StackFrame *>;
2580
2581REGISTER_MAP_WITH_PROGRAMSTATE(ObjCForHasMoreIterations, ObjCForLctxPair, bool)
2582
2584 ProgramStateRef State, const ObjCForCollectionStmt *O, const StackFrame *SF,
2585 bool HasMoreIteraton) {
2586 assert(!State->contains<ObjCForHasMoreIterations>({O, SF}));
2587 return State->set<ObjCForHasMoreIterations>({O, SF}, HasMoreIteraton);
2588}
2589
2591 const ObjCForCollectionStmt *O,
2592 const StackFrame *SF) {
2593 assert(State->contains<ObjCForHasMoreIterations>({O, SF}));
2594 return State->remove<ObjCForHasMoreIterations>({O, SF});
2595}
2596
2598 const ObjCForCollectionStmt *O,
2599 const StackFrame *SF) {
2600 assert(State->contains<ObjCForHasMoreIterations>({O, SF}));
2601 return *State->get<ObjCForHasMoreIterations>({O, SF});
2602}
2603
2604/// Split the state on whether there are any more iterations left for this loop.
2605/// Returns a (HasMoreIteration, HasNoMoreIteration) pair, or std::nullopt when
2606/// the acquisition of the loop condition value failed.
2607static std::optional<std::pair<ProgramStateRef, ProgramStateRef>>
2608assumeCondition(const Stmt *ConditionStmt, ExplodedNode *N) {
2609 ProgramStateRef State = N->getState();
2610 if (const auto *ObjCFor = dyn_cast<ObjCForCollectionStmt>(ConditionStmt)) {
2611 bool HasMoreIteraton =
2612 ExprEngine::hasMoreIteration(State, ObjCFor, N->getStackFrame());
2613 // Checkers have already ran on branch conditions, so the current
2614 // information as to whether the loop has more iteration becomes outdated
2615 // after this point.
2616 State =
2617 ExprEngine::removeIterationState(State, ObjCFor, N->getStackFrame());
2618 if (HasMoreIteraton)
2619 return std::pair<ProgramStateRef, ProgramStateRef>{State, nullptr};
2620 else
2621 return std::pair<ProgramStateRef, ProgramStateRef>{nullptr, State};
2622 }
2623
2624 const auto *ConditionExpr = dyn_cast<Expr>(ConditionStmt);
2625 assert(ConditionExpr && "The condition must be an Expr from here!");
2626
2627 SVal X = State->getSVal(ConditionExpr, N->getStackFrame());
2628
2629 if (X.isUnknownOrUndef()) {
2630 // Give it a chance to recover from unknown.
2631 if (const auto *Ex = dyn_cast<Expr>(ConditionExpr)) {
2632 if (Ex->getType()->isIntegralOrEnumerationType()) {
2633 // Try to recover some path-sensitivity. Right now casts of symbolic
2634 // integers that promote their values are currently not tracked well.
2635 // If 'ConditionExpr' is such an expression, try and recover the
2636 // underlying value and use that instead.
2637 SVal recovered =
2638 RecoverCastedSymbol(State, ConditionExpr, N->getStackFrame(),
2639 N->getState()->getStateManager().getContext());
2640
2641 if (!recovered.isUnknown()) {
2642 X = recovered;
2643 }
2644 }
2645 }
2646 }
2647
2648 // If the condition is still unknown, give up.
2649 if (X.isUnknownOrUndef())
2650 return std::nullopt;
2651
2652 DefinedSVal V = X.castAs<DefinedSVal>();
2653
2654 return State->assume(V);
2655}
2656
2658 const Stmt *Condition, ExplodedNode *Pred, ExplodedNodeSet &Dst,
2659 const CFGBlock *DstT, const CFGBlock *DstF,
2660 std::optional<unsigned> IterationsCompletedInLoop) {
2662 "CXXBindTemporaryExprs are handled by processBindTemporary.");
2663
2664 const StackFrame *SF = Pred->getStackFrame();
2665
2666 // Check for NULL conditions; e.g. "for(;;)"
2667 if (!Condition) {
2668 if (!DstT) {
2669 // I _hope_ that this "null condition + null transition to loop body"
2670 // case is impossible, but I cannot prove this, so let's cover it.
2671 return;
2672 }
2673 BlockEdge BE(getCurrBlock(), DstT, SF);
2674 Dst.insert(Engine.makeNode(BE, Pred->getState(), Pred));
2675 return;
2676 }
2677
2678 if (const auto *Ex = dyn_cast<Expr>(Condition))
2679 Condition = Ex->IgnoreParens();
2680
2682 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
2683 Condition->getBeginLoc(),
2684 "Error evaluating branch");
2685
2686 ExplodedNodeSet CheckersOutSet;
2688 Pred, *this);
2689 // We generated only sinks.
2690 if (CheckersOutSet.empty())
2691 return;
2692
2693 for (ExplodedNode *PredN : CheckersOutSet) {
2694 ProgramStateRef PrevState = PredN->getState();
2695
2696 ProgramStateRef StTrue = PrevState, StFalse = PrevState;
2697 if (const auto KnownCondValueAssumption = assumeCondition(Condition, PredN))
2698 std::tie(StTrue, StFalse) = *KnownCondValueAssumption;
2699
2700 if (StTrue && StFalse)
2702
2703 // We want to ensure consistent behavior between `eagerly-assume=false`,
2704 // when the state split is always performed by the `assumeCondition()`
2705 // call within this function and `eagerly-assume=true` (the default), when
2706 // some conditions (comparison operators, unary negation) can trigger a
2707 // state split before this callback. There are some contrived corner cases
2708 // that behave differently with and without `eagerly-assume`, but I don't
2709 // know about an example that could plausibly appear in "real" code.
2710 bool BothFeasible =
2711 (StTrue && StFalse) ||
2712 didEagerlyAssumeBifurcateAt(PrevState, dyn_cast<Expr>(Condition));
2713
2714 if (StTrue) {
2715 // In a loop, if both branches are feasible (i.e. the analyzer doesn't
2716 // understand the loop condition) and two iterations have already been
2717 // completed, then don't assume a third iteration because it is a
2718 // redundant execution path (unlikely to be different from earlier loop
2719 // exits) and can cause false positives if e.g. the loop iterates over a
2720 // two-element structure with an opaque condition.
2721 //
2722 // The iteration count "2" is hardcoded because it's the natural limit:
2723 // * the fact that the programmer wrote a loop (and not just an `if`)
2724 // implies that they thought that the loop body might be executed twice;
2725 // * however, there are situations where the programmer knows that there
2726 // are at most two iterations but writes a loop that appears to be
2727 // generic, because there is no special syntax for "loop with at most
2728 // two iterations". (This pattern is common in FFMPEG and appears in
2729 // many other projects as well.)
2730 bool CompletedTwoIterations = IterationsCompletedInLoop.value_or(0) >= 2;
2731 bool SkipTrueBranch = BothFeasible && CompletedTwoIterations;
2732
2733 // FIXME: This "don't assume third iteration" heuristic partially
2734 // conflicts with the widen-loop analysis option (which is off by
2735 // default). If we intend to support and stabilize the loop widening,
2736 // we must ensure that it 'plays nicely' with this logic.
2737 if (!SkipTrueBranch || AMgr.options.ShouldWidenLoops) {
2738 if (DstT) {
2739 BlockEdge BE(getCurrBlock(), DstT, SF);
2740 Dst.insert(Engine.makeNode(BE, StTrue, PredN));
2741 }
2742 } else if (!AMgr.options.InlineFunctionsWithAmbiguousLoops) {
2743 // FIXME: There is an ancient and arbitrary heuristic in
2744 // `ExprEngine::processCFGBlockEntrance` which prevents all further
2745 // inlining of a function if it finds an execution path within that
2746 // function which reaches the `MaxBlockVisitOnPath` limit (a/k/a
2747 // `analyzer-max-loop`, by default four iterations in a loop). Adding
2748 // this "don't assume third iteration" logic significantly increased
2749 // the analysis runtime on some inputs because less functions were
2750 // arbitrarily excluded from being inlined, so more entry points used
2751 // up their full allocated budget. As a hacky compensation for this,
2752 // here we apply the "should not inline" mark in cases when the loop
2753 // could potentially reach the `MaxBlockVisitOnPath` limit without the
2754 // "don't assume third iteration" logic. This slightly overcompensates
2755 // (activates if the third iteration can be entered, and will not
2756 // recognize cases where the fourth iteration would't be completed), but
2757 // should be good enough for practical purposes.
2758 if (!SF->inTopFrame()) {
2759 Engine.FunctionSummaries->markShouldNotInline(SF->getDecl());
2760 }
2761 }
2762 }
2763
2764 if (StFalse) {
2765 // In a loop, if both branches are feasible (i.e. the analyzer doesn't
2766 // understand the loop condition), we are before the first iteration and
2767 // the analyzer option `assume-at-least-one-iteration` is set to `true`,
2768 // then avoid creating the execution path where the loop is skipped.
2769 //
2770 // In some situations this "loop is skipped" execution path is an
2771 // important corner case that may evade the notice of the developer and
2772 // hide significant bugs -- however, there are also many situations where
2773 // it's guaranteed that at least one iteration will happen (e.g. some
2774 // data structure is always nonempty), but the analyzer cannot realize
2775 // this and will produce false positives when it assumes that the loop is
2776 // skipped.
2777 bool BeforeFirstIteration = IterationsCompletedInLoop == std::optional{0};
2778 bool SkipFalseBranch = BothFeasible && BeforeFirstIteration &&
2779 AMgr.options.ShouldAssumeAtLeastOneIteration;
2780 if (!SkipFalseBranch && DstF) {
2781 BlockEdge BE(getCurrBlock(), DstF, SF);
2782 Dst.insert(Engine.makeNode(BE, StFalse, PredN));
2783 }
2784 }
2785 }
2786}
2787
2788/// The GDM component containing the set of global variables which have been
2789/// previously initialized with explicit initializers.
2791 llvm::ImmutableSet<const VarDecl *>)
2792
2794 ExplodedNode *Pred,
2795 ExplodedNodeSet &Dst,
2796 const CFGBlock *DstT,
2797 const CFGBlock *DstF) {
2798 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
2799 ProgramStateRef State = Pred->getState();
2800 bool InitHasRun = State->contains<InitializedGlobalsSet>(VD);
2801 if (!InitHasRun)
2802 State = State->add<InitializedGlobalsSet>(VD);
2803
2804 if (const CFGBlock *DstBlock = InitHasRun ? DstT : DstF) {
2805 BlockEdge BE(getCurrBlock(), DstBlock, Pred->getStackFrame());
2806 Dst.insert(Engine.makeNode(BE, State, Pred));
2807 }
2808}
2809
2810/// processIndirectGoto - Called by CoreEngine. Used to generate successor
2811/// nodes by processing the 'effects' of a computed goto jump.
2813 const CFGBlock *Dispatch,
2814 ExplodedNode *Pred) {
2815 ProgramStateRef State = Pred->getState();
2816 SVal V = State->getSVal(Tgt, getCurrStackFrame());
2817
2818 // We cannot dispatch anywhere if the label is undefined, NULL or some other
2819 // concrete number.
2820 // FIXME: Emit a warning in this situation.
2822 return;
2823
2824 // If 'V' is the address of a concrete goto label (on this execution path),
2825 // then only transition along the edge to that label.
2826 // FIXME: Implement dispatch for symbolic pointers, utilizing information
2827 // that they are equal or not equal to pointers to a certain goto label.
2828 const LabelDecl *L = nullptr;
2829 if (auto LV = V.getAs<loc::GotoLabel>())
2830 L = LV->getLabel();
2831
2832 // Dispatch to the label 'L' or to all labels if 'L' is null.
2833 for (const CFGBlock *Succ : Dispatch->succs()) {
2834 if (!L || cast<LabelStmt>(Succ->getLabel())->getDecl() == L) {
2835 // FIXME: If 'V' was a symbolic value, then record that on this execution
2836 // path it is equal to the address of the label leading to 'Succ'.
2837 BlockEdge BE(getCurrBlock(), Succ, Pred->getStackFrame());
2838 Dst.insert(Engine.makeNode(BE, State, Pred));
2839 }
2840 }
2841}
2842
2844 ExplodedNodeSet &Dst,
2845 const BlockEdge &L) {
2846 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
2847}
2848
2849/// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
2850/// nodes when the control reaches the end of a function.
2852 const ReturnStmt *RS) {
2853 ProgramStateRef State = Pred->getState();
2854
2855 if (!Pred->getStackFrame()->inTopFrame())
2856 State = finishArgumentConstruction(
2857 State, *getStateManager().getCallEventManager().getCaller(
2858 Pred->getStackFrame(), Pred->getState()));
2859
2860 // FIXME: We currently cannot assert that temporaries are clear, because
2861 // lifetime extended temporaries are not always modelled correctly. In some
2862 // cases when we materialize the temporary, we do
2863 // createTemporaryRegionIfNeeded(), and the region changes, and also the
2864 // respective destructor becomes automatic from temporary. So for now clean up
2865 // the state manually before asserting. Ideally, this braced block of code
2866 // should go away.
2867 {
2868 const StackFrame *FromSF = Pred->getStackFrame();
2869 const StackFrame *ToSF = FromSF->getParent();
2870 const StackFrame *SF = FromSF;
2871 while (SF != ToSF) {
2872 assert(SF && "ToSF must be a parent of FromSF!");
2873 for (auto I : State->get<ObjectsUnderConstruction>())
2874 if (I.first.getStackFrame() == SF) {
2875 // The comment above only pardons us for not cleaning up a
2876 // temporary destructor. If any other statements are found here,
2877 // it must be a separate problem.
2878 assert(I.first.getItem().getKind() ==
2880 I.first.getItem().getKind() ==
2882 State = State->remove<ObjectsUnderConstruction>(I.first);
2883 }
2884 SF = SF->getParent();
2885 }
2886 }
2887
2888 // Perform the transition with cleanups.
2889 if (State != Pred->getState()) {
2890 Pred = Engine.makeNode(Pred->getLocation(), State, Pred);
2891 if (!Pred) {
2892 // The node with clean temporaries already exists. We might have reached
2893 // it on a path on which we initialize different temporaries.
2894 return;
2895 }
2896 }
2897
2898 assert(areAllObjectsFullyConstructed(Pred->getState(), Pred->getStackFrame(),
2899 Pred->getStackFrame()->getParent()));
2900 ExplodedNodeSet Dst;
2901 if (Pred->getStackFrame()->inTopFrame()) {
2902 // Remove dead symbols.
2903 ExplodedNodeSet AfterRemovedDead;
2904 removeDeadOnEndOfFunction(Pred, AfterRemovedDead);
2905
2906 // Notify checkers.
2907 for (const auto I : AfterRemovedDead)
2908 getCheckerManager().runCheckersForEndFunction(Dst, I, *this, RS);
2909 } else {
2910 getCheckerManager().runCheckersForEndFunction(Dst, Pred, *this, RS);
2911 }
2912
2913 Engine.enqueueEndOfFunction(Dst, RS);
2914}
2915
2916/// ProcessSwitch - Called by CoreEngine. Used to generate successor
2917/// nodes by processing the 'effects' of a switch statement.
2919 ExplodedNodeSet &Dst) {
2920 const ASTContext &ACtx = getContext();
2921 const StackFrame *SF = Pred->getStackFrame();
2922 const Expr *Condition = Switch->getCond();
2923
2924 // The block that is terminated by the switch statement.
2925 const CFGBlock *SwitchBlock = getCurrBlock();
2926 // Note that successors may be null if they are pruned as unreachable.
2927 assert(SwitchBlock->succ_size() && "Switch must have at least one successor");
2928 // The reversed iteration order is present since the beginning, when in 2008
2929 // commit 80ebc1d1c95704b0ff0386b3a3cbc8b3ff960654 added support for handling
2930 // switch statements. I don't see any advantage over regular forward
2931 // iteration -- but switching the order would perturb the insertion order of
2932 // the work list and therefore the analysis results.
2933 llvm::iterator_range<CFGBlock::const_succ_reverse_iterator> CaseBlocks(
2934 SwitchBlock->succ_rbegin() + 1, SwitchBlock->succ_rend());
2935 const CFGBlock *DefaultBlock = *SwitchBlock->succ_rbegin();
2936
2937 ExplodedNodeSet CheckersOutSet;
2938
2940 Condition->IgnoreParens(), CheckersOutSet, Pred, *this);
2941
2942 for (ExplodedNode *Node : CheckersOutSet) {
2943 ProgramStateRef State = Node->getState();
2944
2945 SVal CondV = State->getSVal(Condition, SF);
2946 if (CondV.isUndef()) {
2947 // This can only happen if core.uninitialized.Branch is disabled.
2948 continue;
2949 }
2950 std::optional<NonLoc> CondNL = CondV.getAs<NonLoc>();
2951
2952 for (const CFGBlock *CaseBlock : CaseBlocks) {
2953 // Successor may be pruned out during CFG construction.
2954 if (!CaseBlock)
2955 continue;
2956
2957 const CaseStmt *Case = cast<CaseStmt>(CaseBlock->getLabel());
2958
2959 // Evaluate the LHS of the case value.
2960 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(ACtx);
2961 assert(V1.getBitWidth() ==
2962 getContext().getIntWidth(Condition->getType()));
2963
2964 // Get the RHS of the case, if it exists.
2965 llvm::APSInt V2;
2966 if (const Expr *E = Case->getRHS())
2967 V2 = E->EvaluateKnownConstInt(ACtx);
2968 else
2969 V2 = V1;
2970
2971 ProgramStateRef StateMatching;
2972 if (CondNL) {
2973 // Split the state: this "case:" matches / does not match.
2974 std::tie(StateMatching, State) =
2975 State->assumeInclusiveRange(*CondNL, V1, V2);
2976 } else {
2977 // The switch condition is UnknownVal, so we enter each "case:" without
2978 // any state update.
2979 StateMatching = State;
2980 }
2981
2982 if (StateMatching) {
2983 BlockEdge BE(SwitchBlock, CaseBlock, SF);
2984 Dst.insert(Engine.makeNode(BE, StateMatching, Node));
2985 }
2986
2987 // If _not_ entering the current case is infeasible, then we are done
2988 // with processing the paths through the current Node.
2989 if (!State)
2990 break;
2991 }
2992 if (!State)
2993 continue;
2994
2995 // The default block may be null if it is "optimized out" by CFG creation.
2996 if (!DefaultBlock)
2997 continue;
2998
2999 // If we have switch(enum value), the default branch is not
3000 // feasible if all of the enum constants not covered by 'case:' statements
3001 // are not feasible values for the switch condition.
3002 //
3003 // Note that this isn't as accurate as it could be. Even if there isn't
3004 // a case for a particular enum value as long as that enum value isn't
3005 // feasible then it shouldn't be considered for making 'default:' reachable.
3006 if (Condition->IgnoreParenImpCasts()->getType()->isEnumeralType()) {
3007 if (Switch->isAllEnumCasesCovered())
3008 continue;
3009 }
3010
3011 BlockEdge BE(SwitchBlock, DefaultBlock, SF);
3012 Dst.insert(Engine.makeNode(BE, State, Node));
3013 }
3014}
3015
3016//===----------------------------------------------------------------------===//
3017// Transfer functions: Loads and stores.
3018//===----------------------------------------------------------------------===//
3019
3021 ExplodedNode *Pred,
3022 ExplodedNodeSet &Dst) {
3023 ProgramStateRef state = Pred->getState();
3024 const StackFrame *SF = Pred->getStackFrame();
3025
3026 auto resolveAsLambdaCapturedVar =
3027 [&](const ValueDecl *VD) -> std::optional<std::pair<SVal, QualType>> {
3028 const auto *MD = dyn_cast<CXXMethodDecl>(SF->getDecl());
3029 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
3030 if (AMgr.options.ShouldInlineLambdas && DeclRefEx &&
3031 DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
3032 MD->getParent()->isLambda()) {
3033 // Lookup the field of the lambda.
3034 const CXXRecordDecl *CXXRec = MD->getParent();
3035 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
3036 FieldDecl *LambdaThisCaptureField;
3037 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
3038
3039 // Sema follows a sequence of complex rules to determine whether the
3040 // variable should be captured.
3041 if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
3042 Loc CXXThis = svalBuilder.getCXXThis(MD, SF);
3043 SVal CXXThisVal = state->getSVal(CXXThis);
3044 return std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
3045 }
3046 }
3047
3048 return std::nullopt;
3049 };
3050
3051 if (const auto *VD = dyn_cast<VarDecl>(D)) {
3052 // C permits "extern void v", and if you cast the address to a valid type,
3053 // you can even do things with it. We simply pretend
3054 assert(Ex->isGLValue() || VD->getType()->isVoidType());
3055 std::optional<std::pair<SVal, QualType>> VInfo =
3056 resolveAsLambdaCapturedVar(VD);
3057
3058 if (!VInfo)
3059 VInfo = std::make_pair(state->getLValue(VD, SF), VD->getType());
3060
3061 SVal V = VInfo->first;
3062 bool IsReference = VInfo->second->isReferenceType();
3063
3064 // For references, the 'lvalue' is the pointer address stored in the
3065 // reference region.
3066 if (IsReference) {
3067 if (const MemRegion *R = V.getAsRegion())
3068 V = state->getSVal(R);
3069 else
3070 V = UnknownVal();
3071 }
3072
3073 Dst.insert(
3074 Engine.makeNodeWithBinding(Pred, Ex, V, ProgramPoint::PostLValueKind));
3075 return;
3076 }
3077 if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
3078 assert(!Ex->isGLValue());
3079 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
3080 Dst.insert(Engine.makeNodeWithBinding(Pred, Ex, V));
3081 return;
3082 }
3083 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3084 SVal V = svalBuilder.getFunctionPointer(FD);
3085 Dst.insert(
3086 Engine.makeNodeWithBinding(Pred, Ex, V, ProgramPoint::PostLValueKind));
3087 return;
3088 }
3090 // Delegate all work related to pointer to members to the surrounding
3091 // operator&.
3092 Dst.insert(Pred);
3093 return;
3094 }
3095 if (const auto *BD = dyn_cast<BindingDecl>(D)) {
3096 // Handle structured bindings captured by lambda.
3097 if (std::optional<std::pair<SVal, QualType>> VInfo =
3098 resolveAsLambdaCapturedVar(BD)) {
3099 auto [V, T] = VInfo.value();
3100
3101 if (T->isReferenceType()) {
3102 if (const MemRegion *R = V.getAsRegion())
3103 V = state->getSVal(R);
3104 else
3105 V = UnknownVal();
3106 }
3107
3108 Dst.insert(Engine.makeNodeWithBinding(Pred, Ex, V,
3110 return;
3111 }
3112
3113 const auto *DD = cast<DecompositionDecl>(BD->getDecomposedDecl());
3114
3115 SVal Base = state->getLValue(DD, SF);
3116 if (DD->getType()->isReferenceType()) {
3117 if (const MemRegion *R = Base.getAsRegion())
3118 Base = state->getSVal(R);
3119 else
3120 Base = UnknownVal();
3121 }
3122
3123 SVal V = UnknownVal();
3124
3125 // Handle binding to data members
3126 if (const auto *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
3127 const auto *Field = cast<FieldDecl>(ME->getMemberDecl());
3128 V = state->getLValue(Field, Base);
3129 }
3130 // Handle binding to arrays
3131 else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
3132 SVal Idx = state->getSVal(ASE->getIdx(), SF);
3133
3134 // Note: the index of an element in a structured binding is automatically
3135 // created and it is a unique identifier of the specific element. Thus it
3136 // cannot be a value that varies at runtime.
3137 assert(Idx.isConstant() && "BindingDecl array index is not a constant!");
3138
3139 V = state->getLValue(BD->getType(), Idx, Base);
3140 }
3141 // Handle binding to tuple-like structures
3142 else if (const auto *HV = BD->getHoldingVar()) {
3143 V = state->getLValue(HV, SF);
3144
3145 if (HV->getType()->isReferenceType()) {
3146 if (const MemRegion *R = V.getAsRegion())
3147 V = state->getSVal(R);
3148 else
3149 V = UnknownVal();
3150 }
3151 } else
3152 llvm_unreachable("An unknown case of structured binding encountered!");
3153
3154 // In case of tuple-like types the references are already handled, so we
3155 // don't want to handle them again.
3156 if (BD->getType()->isReferenceType() && !BD->getHoldingVar()) {
3157 if (const MemRegion *R = V.getAsRegion())
3158 V = state->getSVal(R);
3159 else
3160 V = UnknownVal();
3161 }
3162
3163 Dst.insert(
3164 Engine.makeNodeWithBinding(Pred, Ex, V, ProgramPoint::PostLValueKind));
3165 return;
3166 }
3167
3168 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
3169 // FIXME: We should meaningfully implement this.
3170 (void)TPO;
3171 Dst.insert(Pred);
3172 return;
3173 }
3174
3175 llvm_unreachable("Support for this Decl not implemented.");
3176}
3177
3178/// VisitArrayInitLoopExpr - Transfer function for array init loop.
3180 ExplodedNode *Pred,
3181 ExplodedNodeSet &Dst) {
3182 const Expr *Arr = Ex->getCommonExpr()->getSourceExpr();
3183
3184 ExplodedNodeSet CheckerPreStmt;
3185 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, Ex, *this);
3186
3187 ExplodedNodeSet EvalSet;
3188 if (isa<CXXConstructExpr>(Ex->getSubExpr())) {
3189 // The constructor visitor has already handled everything, so let's skip
3190 // forward to PostStmt handling by clearing the range of the 'for' loop.
3191 EvalSet.insert(CheckerPreStmt);
3192 CheckerPreStmt.clear();
3193 }
3194
3195 for (auto *Node : CheckerPreStmt) {
3196 const StackFrame *SF = Node->getStackFrame();
3197 ProgramStateRef state = Node->getState();
3198
3199 SVal Base = UnknownVal();
3200
3201 // As in case of this expression the sub-expressions are not visited by any
3202 // other transfer functions, they are handled by matching their AST.
3203
3204 // Case of implicit copy or move ctor of object with array member
3205 //
3206 // Note: ExprEngine::VisitMemberExpr is not able to bind the array to the
3207 // environment.
3208 //
3209 // struct S {
3210 // int arr[2];
3211 // };
3212 //
3213 //
3214 // S a;
3215 // S b = a;
3216 //
3217 // The AST in case of a *copy constructor* looks like this:
3218 // ArrayInitLoopExpr
3219 // |-OpaqueValueExpr
3220 // | `-MemberExpr <-- match this
3221 // | `-DeclRefExpr
3222 // ` ...
3223 //
3224 //
3225 // S c;
3226 // S d = std::move(d);
3227 //
3228 // In case of a *move constructor* the resulting AST looks like:
3229 // ArrayInitLoopExpr
3230 // |-OpaqueValueExpr
3231 // | `-MemberExpr <-- match this first
3232 // | `-CXXStaticCastExpr <-- match this after
3233 // | `-DeclRefExpr
3234 // ` ...
3235 if (const auto *ME = dyn_cast<MemberExpr>(Arr)) {
3236 Expr *MEBase = ME->getBase();
3237
3238 // Move ctor
3239 if (auto CXXSCE = dyn_cast<CXXStaticCastExpr>(MEBase)) {
3240 MEBase = CXXSCE->getSubExpr();
3241 }
3242
3243 auto ObjDeclExpr = cast<DeclRefExpr>(MEBase);
3244 SVal Obj = state->getLValue(cast<VarDecl>(ObjDeclExpr->getDecl()), SF);
3245
3246 Base = state->getLValue(cast<FieldDecl>(ME->getMemberDecl()), Obj);
3247 }
3248
3249 // Case of lambda capture and decomposition declaration
3250 //
3251 // int arr[2];
3252 //
3253 // [arr]{ int a = arr[0]; }();
3254 // auto[a, b] = arr;
3255 //
3256 // In both of these cases the AST looks like the following:
3257 // ArrayInitLoopExpr
3258 // |-OpaqueValueExpr
3259 // | `-DeclRefExpr <-- match this
3260 // ` ...
3261 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arr))
3262 Base = state->getLValue(cast<VarDecl>(DRE->getDecl()), SF);
3263
3264 // Create a lazy compound value to the original array
3265 if (const MemRegion *R = Base.getAsRegion())
3266 Base = state->getSVal(R);
3267 else
3268 Base = UnknownVal();
3269
3270 EvalSet.insert(Engine.makeNodeWithBinding(Node, Ex, Base));
3271 }
3272
3273 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
3274}
3275
3276/// VisitArraySubscriptExpr - Transfer function for array accesses
3278 ExplodedNode *Pred,
3279 ExplodedNodeSet &Dst){
3280 const Expr *Base = A->getBase()->IgnoreParens();
3281 const Expr *Idx = A->getIdx()->IgnoreParens();
3282
3283 ExplodedNodeSet CheckerPreStmt;
3284 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
3285
3286 ExplodedNodeSet EvalSet;
3287
3288 bool IsVectorType = A->getBase()->getType()->isVectorType();
3289
3290 // The "like" case is for situations where C standard prohibits the type to
3291 // be an lvalue, e.g. taking the address of a subscript of an expression of
3292 // type "void *".
3293 bool IsGLValueLike = A->isGLValue() ||
3294 (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
3295
3296 for (auto *Node : CheckerPreStmt) {
3297 const StackFrame *SF = Node->getStackFrame();
3298 ProgramStateRef state = Node->getState();
3299
3300 if (IsGLValueLike) {
3301 QualType T = A->getType();
3302
3303 // One of the forbidden LValue types! We still need to have sensible
3304 // symbolic locations to represent this stuff. Note that arithmetic on
3305 // void pointers is a GCC extension.
3306 if (T->isVoidType())
3307 T = getContext().CharTy;
3308
3309 SVal V = state->getLValue(T, state->getSVal(Idx, SF),
3310 state->getSVal(Base, SF));
3311 EvalSet.insert(
3312 Engine.makeNodeWithBinding(Node, A, V, ProgramPoint::PostLValueKind));
3313 } else if (IsVectorType) {
3314 // FIXME: non-glvalue vector reads are not modelled.
3315 EvalSet.insert(Engine.makePostStmtNode(A, state, Node));
3316 } else {
3317 llvm_unreachable("Array subscript should be an lValue when not \
3318a vector and not a forbidden lvalue type");
3319 }
3320 }
3321
3322 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
3323}
3324
3325/// VisitMemberExpr - Transfer function for member expressions.
3327 ExplodedNodeSet &Dst) {
3328 // FIXME: Prechecks eventually go in ::Visit().
3329 ExplodedNodeSet CheckedSet;
3330 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
3331
3332 ExplodedNodeSet EvalSet;
3334
3335 // Handle static member variables and enum constants accessed via
3336 // member syntax.
3338 for (const auto I : CheckedSet)
3339 VisitCommonDeclRefExpr(M, Member, I, EvalSet);
3340 } else {
3341
3342 for (const auto I : CheckedSet) {
3343 ProgramStateRef state = I->getState();
3344 const StackFrame *SF = I->getStackFrame();
3345 Expr *BaseExpr = M->getBase();
3346
3347 // Handle C++ method calls.
3348 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
3349 if (MD->isImplicitObjectMemberFunction())
3350 state = createTemporaryRegionIfNeeded(state, SF, BaseExpr);
3351
3352 SVal MDVal = svalBuilder.getFunctionPointer(MD);
3353
3354 EvalSet.insert(Engine.makeNodeWithBinding(I, M, MDVal, state));
3355 continue;
3356 }
3357
3358 // Handle regular struct fields / member variables.
3359 const SubRegion *MR = nullptr;
3360 state = createTemporaryRegionIfNeeded(state, SF, BaseExpr,
3361 /*Result=*/nullptr,
3362 /*OutRegionWithAdjustments=*/&MR);
3363 SVal baseExprVal =
3364 MR ? loc::MemRegionVal(MR) : state->getSVal(BaseExpr, SF);
3365
3366 // FIXME: Copied from RegionStoreManager::bind()
3367 if (const auto *SR =
3368 dyn_cast_or_null<SymbolicRegion>(baseExprVal.getAsRegion())) {
3369 QualType T = SR->getPointeeStaticType();
3370 baseExprVal =
3371 loc::MemRegionVal(getStoreManager().GetElementZeroRegion(SR, T));
3372 }
3373
3374 const auto *field = cast<FieldDecl>(Member);
3375 SVal L = state->getLValue(field, baseExprVal);
3376
3377 if (M->isGLValue() || M->getType()->isArrayType()) {
3378 // We special-case rvalues of array type because the analyzer cannot
3379 // reason about them, since we expect all regions to be wrapped in Locs.
3380 // We instead treat these as lvalues and assume that they will decay to
3381 // pointers as soon as they are used.
3382 if (!M->isGLValue()) {
3383 assert(M->getType()->isArrayType());
3384 const auto *PE =
3385 dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
3386 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
3387 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
3388 }
3389 }
3390
3391 if (field->getType()->isReferenceType()) {
3392 if (const MemRegion *R = L.getAsRegion())
3393 L = state->getSVal(R);
3394 else
3395 L = UnknownVal();
3396 }
3397
3398 EvalSet.insert(Engine.makeNodeWithBinding(
3399 I, M, L, state, ProgramPoint::PostLValueKind));
3400 } else {
3401 evalLoad(EvalSet, M, M, I, state, L);
3402 }
3403 }
3404 }
3405
3406 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
3407}
3408
3410 ExplodedNodeSet &Dst) {
3411 ExplodedNodeSet AfterPreSet;
3412 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
3413
3414 // For now, treat all the arguments to C11 atomics as escaping.
3415 // FIXME: Ideally we should model the behavior of the atomics precisely here.
3416
3417 ExplodedNodeSet AfterInvalidateSet;
3418
3419 for (const auto I : AfterPreSet) {
3420 ProgramStateRef State = I->getState();
3421 const StackFrame *SF = I->getStackFrame();
3422
3423 SmallVector<SVal, 8> ValuesToInvalidate;
3424 for (const Stmt *SubExpr : AE->children()) {
3425 SVal SubExprVal = State->getSVal(cast<Expr>(SubExpr), SF);
3426 ValuesToInvalidate.push_back(SubExprVal);
3427 }
3428
3429 State = State->invalidateRegions(ValuesToInvalidate, getCFGElementRef(),
3431 /*CausedByPointerEscape*/ true,
3432 /*Symbols=*/nullptr);
3433
3434 AfterInvalidateSet.insert(
3435 Engine.makeNodeWithBinding(I, AE, UnknownVal(), State));
3436 }
3437
3438 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
3439}
3440
3441// A value escapes in four possible cases:
3442// (1) We are binding to something that is not a memory region.
3443// (2) We are binding to a MemRegion that does not have stack storage.
3444// (3) We are binding to a top-level parameter region with a non-trivial
3445// destructor. We won't see the destructor during analysis, but it's there.
3446// (4) We are binding to a MemRegion with stack storage that the store
3447// does not understand.
3449 ProgramStateRef State, ArrayRef<std::pair<SVal, SVal>> LocAndVals,
3450 const StackFrame *SF, PointerEscapeKind Kind, const CallEvent *Call) {
3451 SmallVector<SVal, 8> Escaped;
3452 for (const std::pair<SVal, SVal> &LocAndVal : LocAndVals) {
3453 // Cases (1) and (2).
3454 const MemRegion *MR = LocAndVal.first.getAsRegion();
3455 const MemSpaceRegion *Space = MR ? MR->getMemorySpace(State) : nullptr;
3457 Escaped.push_back(LocAndVal.second);
3458 continue;
3459 }
3460
3461 // Case (3).
3462 if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion()))
3463 if (isa<StackArgumentsSpaceRegion>(Space) &&
3464 VR->getStackFrame()->inTopFrame())
3465 if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl())
3466 if (!RD->hasTrivialDestructor()) {
3467 Escaped.push_back(LocAndVal.second);
3468 continue;
3469 }
3470
3471 // Case (4): in order to test that, generate a new state with the binding
3472 // added. If it is the same state, then it escapes (since the store cannot
3473 // represent the binding).
3474 // Do this only if we know that the store is not supposed to generate the
3475 // same state.
3476 SVal StoredVal = State->getSVal(MR);
3477 if (StoredVal != LocAndVal.second)
3478 if (State ==
3479 (State->bindLoc(loc::MemRegionVal(MR), LocAndVal.second, SF)))
3480 Escaped.push_back(LocAndVal.second);
3481 }
3482
3483 if (Escaped.empty())
3484 return State;
3485
3486 return escapeValues(State, Escaped, Kind, Call);
3487}
3488
3490 SVal Loc, SVal Val,
3491 const StackFrame *SF) {
3492 std::pair<SVal, SVal> LocAndVal(Loc, Val);
3493 return processPointerEscapedOnBind(State, LocAndVal, SF, PSK_EscapeOnBind,
3494 nullptr);
3495}
3496
3499 const InvalidatedSymbols *Invalidated,
3500 ArrayRef<const MemRegion *> ExplicitRegions,
3501 const CallEvent *Call,
3503 if (!Invalidated || Invalidated->empty())
3504 return State;
3505
3506 if (!Call)
3508 *Invalidated,
3509 nullptr,
3511 &ITraits);
3512
3513 // If the symbols were invalidated by a call, we want to find out which ones
3514 // were invalidated directly due to being arguments to the call.
3515 InvalidatedSymbols SymbolsDirectlyInvalidated;
3516 for (const auto I : ExplicitRegions) {
3517 if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
3518 SymbolsDirectlyInvalidated.insert(R->getSymbol());
3519 }
3520
3521 InvalidatedSymbols SymbolsIndirectlyInvalidated;
3522 for (const auto &sym : *Invalidated) {
3523 if (SymbolsDirectlyInvalidated.count(sym))
3524 continue;
3525 SymbolsIndirectlyInvalidated.insert(sym);
3526 }
3527
3528 if (!SymbolsDirectlyInvalidated.empty())
3530 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
3531
3532 // Notify about the symbols that get indirectly invalidated by the call.
3533 if (!SymbolsIndirectlyInvalidated.empty())
3535 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
3536
3537 return State;
3538}
3539
3540/// evalBind - Handle the semantics of binding a value to a specific location.
3541/// This method is used by evalStore, VisitDeclStmt, and others.
3542void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
3543 ExplodedNode *Pred, SVal Location, SVal Val,
3544 bool AtDeclInit, const ProgramPoint *PP) {
3545
3546 // It may be a Loc, UnknownVal or perhaps UndefinedVal.
3547 assert(!isa<NonLoc>(Location) && "evalBind location should not be NonLoc!");
3548
3549 const StackFrame *SF = Pred->getStackFrame();
3550 PostStmt DefaultPP(StoreE, SF);
3551
3552 if (!PP)
3553 PP = &DefaultPP;
3554
3555 // Do a previsit of the bind.
3556 ExplodedNodeSet CheckedSet;
3557 getCheckerManager().runCheckersForBind(CheckedSet, Pred, Location, Val,
3558 StoreE, AtDeclInit, *this, *PP);
3559
3560 for (ExplodedNode *PredI : CheckedSet) {
3561 ProgramStateRef State = PredI->getState();
3562
3563 // Check and record that 'Val' may escape:
3564 State = processPointerEscapedOnBind(State, Location, Val, SF);
3565
3566 if (auto AsLoc = Location.getAs<Loc>()) {
3567 // When binding the value, pass on the hint that this is a
3568 // initialization. For initializations, we do not need to inform clients
3569 // of region changes.
3570 State = State->bindLoc(*AsLoc, Val, SF, /*notifyChanges=*/!AtDeclInit);
3571 }
3572
3573 PostStore PS(StoreE, SF, Location.getAsRegion(), /*tag=*/nullptr);
3574 Dst.insert(Engine.makeNode(PS, State, PredI));
3575 }
3576}
3577
3578/// evalStore - Handle the semantics of a store via an assignment.
3579/// @param Dst The node set to store generated state nodes
3580/// @param AssignE The assignment expression if the store happens in an
3581/// assignment.
3582/// @param LocationE The location expression that is stored to.
3583/// @param state The current simulation state
3584/// @param location The location to store the value
3585/// @param Val The value to be stored
3587 const Expr *LocationE,
3588 ExplodedNode *Pred,
3589 ProgramStateRef state, SVal location, SVal Val,
3590 const ProgramPointTag *tag) {
3591 // Proceed with the store. We use AssignE as the anchor for the PostStore
3592 // ProgramPoint if it is non-NULL, and LocationE otherwise.
3593 const Expr *StoreE = AssignE ? AssignE : LocationE;
3594
3595 // Evaluate the location (checks for bad dereferences).
3596 ExplodedNodeSet Tmp;
3597 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false);
3598
3599 if (Tmp.empty())
3600 return;
3601
3602 if (location.isUndef())
3603 return;
3604
3605 for (const auto I : Tmp)
3606 evalBind(Dst, StoreE, I, location, Val, false);
3607}
3608
3610 const Expr *NodeEx,
3611 const Expr *BoundEx,
3612 ExplodedNode *Pred,
3613 ProgramStateRef state,
3614 SVal location,
3615 const ProgramPointTag *tag,
3616 QualType LoadTy) {
3617 assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
3618 assert(NodeEx);
3619 assert(BoundEx);
3620 // Evaluate the location (checks for bad dereferences).
3621 ExplodedNodeSet Tmp;
3622 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true);
3623 if (Tmp.empty())
3624 return;
3625
3626 if (location.isUndef()) {
3627 Dst.insert(Tmp);
3628 return;
3629 }
3630
3631 // Proceed with the load.
3632 for (const auto I : Tmp) {
3633 state = I->getState();
3634
3635 SVal V = UnknownVal();
3636 if (location.isValid()) {
3637 if (LoadTy.isNull())
3638 LoadTy = BoundEx->getType();
3639 V = state->getSVal(location.castAs<Loc>(), LoadTy);
3640 }
3641
3642 const auto *SF = I->getStackFrame();
3643 PostLoad Loc(NodeEx, SF, tag);
3644 Dst.insert(Engine.makeNode(Loc, state->BindExpr(BoundEx, SF, V), I));
3645 }
3646}
3647
3648void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *NodeEx,
3649 const Stmt *BoundEx, ExplodedNode *Pred,
3650 ProgramStateRef state, SVal location,
3651 bool isLoad) {
3652 // Early checks for performance reason.
3653 if (location.isUnknown()) {
3654 Dst.insert(Pred);
3655 return;
3656 }
3657
3658 ExplodedNodeSet Src;
3659 if (Pred->getState() == state) {
3660 Src.insert(Pred);
3661 } else {
3662 // Associate this new state with an ExplodedNode.
3663 // FIXME: If I pass null tag, the graph is incorrect, e.g for
3664 // int *p;
3665 // p = 0;
3666 // *p = 0xDEADBEEF;
3667 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
3668 // instead "int *p" is noted as
3669 // "Variable 'p' initialized to a null pointer value"
3670
3671 static SimpleProgramPointTag tag(TagProviderName, "Location");
3672 PostStmt Loc(NodeEx, Pred->getStackFrame(), &tag);
3673 Src.insert(Engine.makeNode(Loc, state, Pred));
3674 }
3675
3676 ExplodedNodeSet Tmp;
3677 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
3678 NodeEx, BoundEx, *this);
3679 Dst.insert(Tmp);
3680}
3681
3682std::pair<const ProgramPointTag *, const ProgramPointTag *>
3684 static SimpleProgramPointTag TrueTag(TagProviderName, "Eagerly Assume True"),
3685 FalseTag(TagProviderName, "Eagerly Assume False");
3686
3687 return std::make_pair(&TrueTag, &FalseTag);
3688}
3689
3690/// If the last EagerlyAssume attempt was successful (i.e. the true and false
3691/// cases were both feasible), this state trait stores the expression where it
3692/// happened; otherwise this holds nullptr.
3693REGISTER_TRAIT_WITH_PROGRAMSTATE(LastEagerlyAssumeExprIfSuccessful,
3694 const Expr *)
3695
3697 ExplodedNodeSet &Src,
3698 const Expr *Ex) {
3699 for (ExplodedNode *Pred : Src) {
3700 const StackFrame *SF = Pred->getStackFrame();
3701 // Test if the previous node was as the same expression. This can happen
3702 // when the expression fails to evaluate to anything meaningful and
3703 // (as an optimization) we don't generate a node.
3704 ProgramPoint P = Pred->getLocation();
3705 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
3706 Dst.insert(Pred);
3707 continue;
3708 }
3709
3710 ProgramStateRef State = Pred->getState();
3711 State = State->set<LastEagerlyAssumeExprIfSuccessful>(nullptr);
3712 SVal V = State->getSVal(Ex, SF);
3713 std::optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
3714 if (SEV && SEV->isExpression()) {
3715 const auto &[TrueTag, FalseTag] = getEagerlyAssumeBifurcationTags();
3716
3717 auto [StateTrue, StateFalse] = State->assume(*SEV);
3718
3719 if (StateTrue && StateFalse) {
3720 StateTrue = StateTrue->set<LastEagerlyAssumeExprIfSuccessful>(Ex);
3721 StateFalse = StateFalse->set<LastEagerlyAssumeExprIfSuccessful>(Ex);
3722 }
3723
3724 // First assume that the condition is true.
3725 if (StateTrue) {
3726 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
3727 StateTrue = StateTrue->BindExpr(Ex, SF, Val);
3728 PostStmt PostStmtTrue(Ex, SF, TrueTag);
3729 Dst.insert(Engine.makeNode(PostStmtTrue, StateTrue, Pred));
3730 }
3731
3732 // Next, assume that the condition is false.
3733 if (StateFalse) {
3734 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
3735 StateFalse = StateFalse->BindExpr(Ex, SF, Val);
3736 PostStmt PostStmtFalse(Ex, SF, FalseTag);
3737 Dst.insert(Engine.makeNode(PostStmtFalse, StateFalse, Pred));
3738 }
3739 } else {
3740 Dst.insert(Pred);
3741 }
3742 }
3743}
3744
3746 const Expr *Ex) const {
3747 return Ex && State->get<LastEagerlyAssumeExprIfSuccessful>() == Ex;
3748}
3749
3751 ExplodedNodeSet &Dst) {
3752 // We have processed both the inputs and the outputs. All of the outputs
3753 // should evaluate to Locs. Nuke all of their values.
3754
3755 // FIXME: Some day in the future it would be nice to allow a "plug-in"
3756 // which interprets the inline asm and stores proper results in the
3757 // outputs.
3758
3759 ProgramStateRef state = Pred->getState();
3760
3761 for (const Expr *O : A->outputs()) {
3762 SVal X = state->getSVal(O, Pred->getStackFrame());
3763 assert(!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef.
3764
3765 if (std::optional<Loc> LV = X.getAs<Loc>())
3766 state = state->invalidateRegions(*LV, getCFGElementRef(),
3768 Pred->getStackFrame(),
3769 /*CausedByPointerEscape=*/true);
3770 }
3771
3772 // Do not reason about locations passed inside inline assembly.
3773 for (const Expr *I : A->inputs()) {
3774 SVal X = state->getSVal(I, Pred->getStackFrame());
3775
3776 if (std::optional<Loc> LV = X.getAs<Loc>())
3777 state = state->invalidateRegions(*LV, getCFGElementRef(),
3779 Pred->getStackFrame(),
3780 /*CausedByPointerEscape=*/true);
3781 }
3782
3783 Dst.insert(Engine.makePostStmtNode(A, state, Pred));
3784}
3785
3787 ExplodedNodeSet &Dst) {
3788 Dst.insert(Engine.makePostStmtNode(A, Pred->getState(), Pred));
3789}
3790
3791//===----------------------------------------------------------------------===//
3792// Visualization.
3793//===----------------------------------------------------------------------===//
3794
3795namespace llvm {
3796
3797template<>
3799 DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3800
3801 static bool nodeHasBugReport(const ExplodedNode *N) {
3802 BugReporter &BR = static_cast<ExprEngine &>(
3803 N->getState()->getStateManager().getOwningEngine()).getBugReporter();
3804
3805 for (const auto &Class : BR.equivalenceClasses()) {
3806 for (const auto &Report : Class.getReports()) {
3807 const auto *PR = dyn_cast<PathSensitiveBugReport>(Report.get());
3808 if (!PR)
3809 continue;
3810 const ExplodedNode *EN = PR->getErrorNode();
3811 if (EN->getState() == N->getState() &&
3812 EN->getLocation() == N->getLocation())
3813 return true;
3814 }
3815 }
3816 return false;
3817 }
3818
3819 /// \p PreCallback: callback before break.
3820 /// \p PostCallback: callback after break.
3821 /// \p Stop: stop iteration if returns @c true
3822 /// \return Whether @c Stop ever returned @c true.
3824 const ExplodedNode *N,
3825 llvm::function_ref<void(const ExplodedNode *)> PreCallback,
3826 llvm::function_ref<void(const ExplodedNode *)> PostCallback,
3827 llvm::function_ref<bool(const ExplodedNode *)> Stop) {
3828 while (true) {
3829 PreCallback(N);
3830 if (Stop(N))
3831 return true;
3832
3833 if (N->succ_size() != 1 || !isNodeHidden(N->getFirstSucc(), nullptr))
3834 break;
3835 PostCallback(N);
3836
3837 N = N->getFirstSucc();
3838 }
3839 return false;
3840 }
3841
3842 static bool isNodeHidden(const ExplodedNode *N, const ExplodedGraph *G) {
3843 return N->isTrivial();
3844 }
3845
3846 static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){
3847 std::string Buf;
3848 llvm::raw_string_ostream Out(Buf);
3849
3850 const bool IsDot = true;
3851 const unsigned int Space = 1;
3852 ProgramStateRef State = N->getState();
3853
3854 Out << "{ \"state_id\": " << State->getID()
3855 << ",\\l";
3856
3857 Indent(Out, Space, IsDot) << "\"program_points\": [\\l";
3858
3859 // Dump program point for all the previously skipped nodes.
3861 N,
3862 [&](const ExplodedNode *OtherNode) {
3863 Indent(Out, Space + 1, IsDot) << "{ ";
3864 OtherNode->getLocation().printJson(Out, /*NL=*/"\\l");
3865 Out << ", \"tag\": ";
3866 if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag())
3867 Out << '\"' << Tag->getDebugTag() << '\"';
3868 else
3869 Out << "null";
3870 Out << ", \"node_id\": " << OtherNode->getID() <<
3871 ", \"is_sink\": " << OtherNode->isSink() <<
3872 ", \"has_report\": " << nodeHasBugReport(OtherNode) << " }";
3873 },
3874 // Adds a comma and a new-line between each program point.
3875 [&](const ExplodedNode *) { Out << ",\\l"; },
3876 [&](const ExplodedNode *) { return false; });
3877
3878 Out << "\\l"; // Adds a new-line to the last program point.
3879 Indent(Out, Space, IsDot) << "],\\l";
3880
3881 State->printDOT(Out, N->getStackFrame(), Space);
3882
3883 Out << "\\l}\\l";
3884 return Buf;
3885 }
3886};
3887
3888} // namespace llvm
3889
3890void ExprEngine::ViewGraph(bool trim) {
3891 std::string Filename = DumpGraph(trim);
3892 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3893}
3894
3896 std::string Filename = DumpGraph(Nodes);
3897 llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3898}
3899
3900std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
3901 if (trim) {
3902 std::vector<const ExplodedNode *> Src;
3903
3904 // Iterate through the reports and get their nodes.
3905 for (const auto &Class : BR.equivalenceClasses()) {
3906 const auto *R =
3907 dyn_cast<PathSensitiveBugReport>(Class.getReports()[0].get());
3908 if (!R)
3909 continue;
3910 const auto *N = const_cast<ExplodedNode *>(R->getErrorNode());
3911 Src.push_back(N);
3912 }
3913 return DumpGraph(Src, Filename);
3914 }
3915
3916 // FIXME(sandboxing): Remove this by adopting `llvm::vfs::OutputBackend`.
3917 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
3918 return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
3919 /*Title=*/"Exploded Graph",
3920 /*Filename=*/std::string(Filename));
3921}
3922
3924 StringRef Filename) {
3925 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
3926
3927 if (!TrimmedG) {
3928 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3929 return "";
3930 }
3931
3932 // FIXME(sandboxing): Remove this by adopting `llvm::vfs::OutputBackend`.
3933 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
3934 return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
3935 /*ShortNames=*/false,
3936 /*Title=*/"Trimmed Exploded Graph",
3937 /*Filename=*/std::string(Filename));
3938}
3939
3941 static int index = 0;
3942 return &index;
3943}
3944
3945void ExprEngine::anchor() { }
3946
3948 bool IsTransparent, ExplodedNode *Pred,
3949 ExplodedNodeSet &Dst) {
3951
3952 const StackFrame *SF = Pred->getStackFrame();
3953
3954 ProgramStateRef S = Pred->getState();
3956
3957 bool IsCompound = T->isArrayType() || T->isRecordType() ||
3958 T->isAnyComplexType() || T->isVectorType();
3959
3960 SVal Val;
3961 if (Args.size() > 1 || (E->isPRValue() && IsCompound && !IsTransparent)) {
3962 llvm::ImmutableList<SVal> ArgList = getBasicVals().getEmptySValList();
3963 for (Expr *E : llvm::reverse(Args))
3964 ArgList = getBasicVals().prependSVal(S->getSVal(E, SF), ArgList);
3965
3966 Val = getSValBuilder().makeCompoundVal(T, ArgList);
3967 } else if (Args.size() == 0) {
3968 Val = getSValBuilder().makeZeroVal(T);
3969 } else {
3970 Val = S->getSVal(Args.front(), SF);
3971 }
3972 Dst.insert(Engine.makeNodeWithBinding(Pred, E, Val));
3973}
Defines the clang::ASTContext interface.
#define V(N, I)
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
#define STAT_COUNTER(VARNAME, DESC)
Defines the clang::Expr interface and subclasses for C++ expressions.
static const Stmt * getRightmostLeaf(const Stmt *Condition)
static void printIndicesOfElementsToConstructJson(raw_ostream &Out, ProgramStateRef State, const char *NL, const StackFrame *SF, unsigned int Space=0, bool IsDot=false)
static const Stmt * ResolveCondition(const Stmt *Condition, const CFGBlock *B)
std::pair< const ObjCForCollectionStmt *, const StackFrame * > ObjCForLctxPair
static SVal RecoverCastedSymbol(ProgramStateRef state, const Stmt *Condition, const StackFrame *SF, ASTContext &Ctx)
RecoverCastedSymbol - A helper function for ProcessBranch that is used to try to recover some path-se...
static void printStateTraitWithStackFrameJson(raw_ostream &Out, ProgramStateRef State, const StackFrame *SF, const char *NL, unsigned int Space, bool IsDot, const char *jsonPropertyName, Printer printer, Args &&...args)
A helper function to generalize program state trait printing.
static void printPendingInitLoopJson(raw_ostream &Out, ProgramStateRef State, const char *NL, const StackFrame *SF, unsigned int Space=0, bool IsDot=false)
REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction, ObjectsUnderConstructionMap) typedef llvm REGISTER_TRAIT_WITH_PROGRAMSTATE(IndexOfElementToConstruct, IndexOfElementToConstructMap) typedef llvm typedef llvm::ImmutableMap< const StackFrame *, unsigned > PendingArrayDestructionMap
llvm::ImmutableMap< ConstructedObjectKey, SVal > ObjectsUnderConstructionMap
static bool shouldRemoveDeadBindings(AnalysisManager &AMgr, const Stmt *S, const ExplodedNode *Pred, const StackFrame *SF)
static void printObjectsUnderConstructionJson(raw_ostream &Out, ProgramStateRef State, const char *NL, const StackFrame *SF, unsigned int Space=0, bool IsDot=false)
static std::optional< std::pair< ProgramStateRef, ProgramStateRef > > assumeCondition(const Stmt *ConditionStmt, ExplodedNode *N)
Split the state on whether there are any more iterations left for this loop.
static void printPendingArrayDestructionsJson(raw_ostream &Out, ProgramStateRef State, const char *NL, const StackFrame *SF, unsigned int Space=0, bool IsDot=false)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
This header contains the declarations of functions which are used to decide which loops should be com...
This header contains the declarations of functions which are used to widen loops which do not otherwi...
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy.
static bool isRecordType(QualType T)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
Defines the Objective-C statement AST node classes.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType CharTy
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:876
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
ASTContext & getASTContext() const
Stores options for the analyzer from the command line.
AnalysisPurgeMode AnalysisPurgeOpt
Represents a loop initializing the elements of an array.
Definition Expr.h:5985
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6000
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6005
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2732
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
outputs_range outputs()
Definition Stmt.h:3429
inputs_range inputs()
Definition Stmt.h:3400
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6945
child_range children()
Definition Expr.h:7084
const CFGBlock * getPreviousBlock() const
const CFGBlock * getBlock() const
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition CFG.h:465
Represents C++ object destructor implicitly generated for base object in destructor.
Definition CFG.h:516
const CXXBaseSpecifier * getBaseSpecifier() const
Definition CFG.h:521
Represents a single basic block in a source-level CFG.
Definition CFG.h:652
succ_reverse_iterator succ_rend()
Definition CFG.h:1043
succ_reverse_iterator succ_rbegin()
Definition CFG.h:1042
succ_range succs()
Definition CFG.h:1047
CFGTerminator getTerminator() const
Definition CFG.h:1132
Stmt * getTerminatorStmt()
Definition CFG.h:1134
unsigned getBlockID() const
Definition CFG.h:1154
unsigned succ_size() const
Definition CFG.h:1055
Represents C++ object destructor generated from a call to delete.
Definition CFG.h:490
Represents a top-level expression in a basic block.
Definition CFG.h:55
@ CleanupFunction
Definition CFG.h:83
@ CXXRecordTypedCall
Definition CFG.h:72
@ FullExprCleanup
Definition CFG.h:62
@ AutomaticObjectDtor
Definition CFG.h:76
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type.
Definition CFG.h:103
Kind getKind() const
Definition CFG.h:122
Represents C++ object destructor implicitly generated by compiler on various occasions.
Definition CFG.h:414
const CXXDestructorDecl * getDestructorDecl(ASTContext &astContext) const
Definition CFG.cpp:5514
Represents C++ base or member initializer from constructor's initialization list.
Definition CFG.h:232
const CXXCtorInitializer * getInitializer() const
Definition CFG.h:237
Represents the point where the lifetime of an automatic object ends.
Definition CFG.h:321
const VarDecl * getVarDecl() const
Definition CFG.h:326
Represents the point where a loop ends.
Definition CFG.h:278
const Stmt * getLoopStmt() const
Definition CFG.h:282
Represents C++ object destructor implicitly generated for member object in destructor.
Definition CFG.h:537
const FieldDecl * getFieldDecl() const
Definition CFG.h:542
Represents C++ allocator call.
Definition CFG.h:252
const CXXNewExpr * getAllocatorExpr() const
Definition CFG.h:258
LLVM_ATTRIBUTE_RETURNS_NONNULL const Stmt * getTriggerStmt() const
Definition CFG.h:300
const Stmt * getStmt() const
Definition CFG.h:143
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition CFG.h:558
const CXXBindTemporaryExpr * getBindTemporaryExpr() const
Definition CFG.h:563
bool isStmtBranch() const
Definition CFG.h:615
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1496
const Expr * getSubExpr() const
Definition ExprCXX.h:1518
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:1522
Represents a call to a C++ constructor.
Definition ExprCXX.h:1551
Represents a C++ base or member initializer.
Definition DeclCXX.h:2402
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition DeclCXX.h:2542
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition DeclCXX.h:2502
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2604
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition DeclCXX.cpp:2953
bool isAnyMemberInitializer() const
Definition DeclCXX.h:2482
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition DeclCXX.h:2474
bool isIndirectMemberInitializer() const
Definition DeclCXX.h:2486
int64_t getID(const ASTContext &Context) const
Definition DeclCXX.cpp:2934
const Type * getBaseClass() const
If this is a base class initializer, returns the type of the base class.
Definition DeclCXX.cpp:2946
FieldDecl * getAnyMember() const
Definition DeclCXX.h:2548
IndirectFieldDecl * getIndirectMember() const
Definition DeclCXX.h:2556
bool isBaseVirtual() const
Returns whether the base is virtual or not.
Definition DeclCXX.h:2528
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2629
bool isArrayForm() const
Definition ExprCXX.h:2655
SourceLocation getBeginLoc() const
Definition ExprCXX.h:2679
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition ExprCXX.cpp:343
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2358
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5140
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5180
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1792
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2129
Represents a point when we begin processing an inlined call.
CaseStmt - Represent a case statement.
Definition Stmt.h:1929
Expr * getLHS()
Definition Stmt.h:2012
Expr * getRHS()
Definition Stmt.h:2024
Represents a single point (AST node) in the program that requires attention during construction of an...
unsigned getIndex() const
If a single trigger statement triggers multiple constructors, they are usually being enumerated.
const CXXCtorInitializer * getCXXCtorInitializer() const
The construction site is not necessarily a statement.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1281
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1640
const Decl * getSingleDecl() const
Definition Stmt.h:1655
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This is a meta program point, which should be skipped by all the diagnostic reasoning etc.
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:287
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3089
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
bool isPRValue() const
Definition Expr.h:285
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3294
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3455
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
Describes an C or C++ initializer list.
Definition Expr.h:5319
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2473
ArrayRef< Expr * > inits() const
Definition Expr.h:5372
Represents the declaration of a label.
Definition Decl.h:524
Represents a point when the lifetime of an automatic object ends.
Represents a point when we exit a loop.
This represents a Microsoft inline-assembly statement extension.
Definition Stmt.h:3674
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3375
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3458
Expr * getBase() const
Definition Expr.h:3452
This represents a decl that may have a name.
Definition Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Represents Objective-C's collection statement.
Definition StmtObjC.h:23
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1239
bool isConsumedExpr(Expr *E) const
Represents a parameter to a function.
Definition Decl.h:1819
Represents a program point just after an implicit call event.
Represents a program point after a store evaluation.
Represents a program point just before an implicit call event.
If a crash happens while one of these objects are live, the message is printed out along with the spe...
ProgramPoints can be "tagged" as representing points specific to a given analysis entity.
const ProgramPointTag * getTag() const
bool isPurgeKind()
Is this a program point corresponding to purge/removal of dead symbols and bindings.
T castAs() const
Convert to the specified ProgramPoint type, asserting that this ProgramPoint is of the desired type.
static ProgramPoint getProgramPoint(const Stmt *S, ProgramPoint::Kind K, const StackFrame *SF, const ProgramPointTag *tag)
void printJson(llvm::raw_ostream &Out, const char *NL="\n") const
ProgramPoint withTag(const ProgramPointTag *tag) const
Create a new ProgramPoint object that is the same as the original except for using the specified tag ...
const StackFrame * getStackFrame() const
std::optional< T > getAs() const
Convert to the specified ProgramPoint type, returning std::nullopt if this ProgramPoint is not of the...
A (possibly-)qualified type.
Definition TypeBase.h:938
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getCanonicalType() const
Definition TypeBase.h:8556
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8525
std::string getAsString() const
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3169
std::string printToString(const SourceManager &SM) const
It represents a stack frame of the call stack.
unsigned getIndex() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
void printJson(raw_ostream &Out, const char *NL="\n", unsigned int Space=0, bool IsDot=false, std::function< void(const StackFrame *)> printMoreInfoPerStackFrame=[](const StackFrame *) {}) const
Prints out the call stack in json format.
const Expr * getCallSite() const
const Decl * getDecl() const
const StackFrame * getParent() const
It might return null.
const CFGBlock * getCallSiteBlock() const
const Stmt * getStmt() const
Stmt - This represents one statement.
Definition Stmt.h:85
@ NoStmtClass
Definition Stmt.h:88
void printJson(raw_ostream &Out, PrinterHelper *Helper, const PrintingPolicy &Policy, bool AddQuotes) const
Pretty-prints in JSON format.
StmtClass getStmtClass() const
Definition Stmt.h:1502
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
const char * getStmtClassName() const
Definition Stmt.cpp:86
int64_t getID(const ASTContext &Context) const
Definition Stmt.cpp:379
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2518
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:8840
bool isReferenceType() const
Definition TypeBase.h:8765
bool isVectorType() const
Definition TypeBase.h:8880
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
This class is used for tools that requires cross translation unit capability.
llvm::ImmutableList< SVal > getEmptySValList()
llvm::ImmutableList< SVal > prependSVal(SVal X, llvm::ImmutableList< SVal > L)
BugReporter is a utility class for generating PathDiagnostics for analysis.
llvm::iterator_range< EQClasses_iterator > equivalenceClasses()
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:152
static bool isCallStmt(const Stmt *S)
Returns true if this is a statement is a function or method call of some kind.
ProgramStateRef runCheckersForRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion * > ExplicitRegions, ArrayRef< const MemRegion * > Regions, const StackFrame *SF, const CallEvent *Call)
Run checkers for region changes.
void runCheckersForLocation(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, bool isLoad, const Stmt *NodeEx, const Stmt *BoundEx, ExprEngine &Eng)
Run checkers for load/store of a location.
void runCheckersForBind(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, SVal val, const Stmt *S, bool AtDeclInit, ExprEngine &Eng, const ProgramPoint &PP)
Run checkers for binding of a value to a location.
void runCheckersForEndAnalysis(ExplodedGraph &G, BugReporter &BR, ExprEngine &Eng)
Run checkers for end of analysis.
void runCheckersForPrintStateJson(raw_ostream &Out, ProgramStateRef State, const char *NL="\n", unsigned int Space=0, bool IsDot=false) const
Run checkers for debug-printing a ProgramState.
void runCheckersForDeadSymbols(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SymbolReaper &SymReaper, const Stmt *S, ExprEngine &Eng, ProgramPoint::Kind K)
Run checkers for dead symbols.
void runCheckersForEndFunction(ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng, const ReturnStmt *RS)
Run checkers on end of function.
void runCheckersForLiveSymbols(ProgramStateRef state, SymbolReaper &SymReaper)
Run checkers for live symbols.
void runCheckersForBeginFunction(ExplodedNodeSet &Dst, const BlockEdge &L, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers on beginning of function.
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
void runCheckersForBlockEntrance(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const BlockEntrance &Entrance, ExprEngine &Eng) const
Run checkers after taking a control flow edge.
void runCheckersForBranchCondition(const Stmt *condition, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng)
Run checkers for branch condition.
ProgramStateRef runCheckersForPointerEscape(ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits)
Run checkers when pointers escape.
void runCheckersForLifetimeEnd(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const VarDecl *Decl, ExprEngine &Eng)
Run checkers for the end of a variable's lifetime.
ProgramStateRef runCheckersForEvalAssume(ProgramStateRef state, SVal Cond, bool Assumption)
Run checkers for handling assumptions on symbolic values.
virtual ProgramStateRef removeDeadBindings(ProgramStateRef state, SymbolReaper &SymReaper)=0
Scan all symbols referenced by the constraints.
void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Idx)
Enqueue a single node created as a result of statement processing.
ExplodedNode * makeNode(const ProgramPoint &Loc, ProgramStateRef State, ExplodedNode *Pred, bool MarkAsSink=false) const
ExplodedNode * getNode(const ProgramPoint &L, ProgramStateRef State, bool IsSink=false, bool *IsNew=nullptr)
Retrieve the node associated with a (Location, State) pair, where the 'Location' is a ProgramPoint in...
ExplodedNodeSet is a set of ExplodedNode * elements with the invariant that its elements cannot be nu...
void insert(ExplodedNode *N)
const ProgramStateRef & getState() const
bool isTrivial() const
The node is trivial if it has only one successor, only one predecessor, it's predecessor has only one...
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
void addPredecessor(ExplodedNode *V, ExplodedGraph &G)
addPredeccessor - Adds a predecessor to the current node, and in tandem add this node as a successor ...
ExplodedNode * getFirstSucc()
unsigned succ_size() const
const StackFrame * getStackFrame() const
void VisitBinaryOperator(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBinaryOperator - Transfer function logic for binary operators.
const StackFrame * getRootStackFrame() const
Definition ExprEngine.h:268
ProgramStateManager & getStateManager()
Definition ExprEngine.h:477
void processCFGElement(const CFGElement E, ExplodedNode *Pred, unsigned StmtIdx)
processCFGElement - Called by CoreEngine.
void processBranch(const Stmt *Condition, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF, std::optional< unsigned > IterationsCompletedInLoop)
ProcessBranch - Called by CoreEngine.
void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitArraySubscriptExpr - Transfer function for array accesses.
void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred)
void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void ProcessTemporaryDtor(const CFGTemporaryDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out, const Stmt *ReferenceStmt, const StackFrame *SF, const Stmt *DiagnosticStmt=nullptr, ProgramPoint::Kind K=ProgramPoint::PreStmtPurgeDeadSymbolsKind)
Run the analyzer's garbage collection - remove dead symbols and bindings from the state.
void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGuardedExpr - Transfer function logic for ?, __builtin_choose.
void runCheckersForBlockEntrance(const BlockEntrance &Entrance, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCast - Transfer function logic for all casts (implicit and explicit).
BasicValueFactory & getBasicVals()
Definition ExprEngine.h:493
void VisitLogicalExpr(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLogicalExpr - Transfer function logic for '&&', '||'.
void processEndOfFunction(ExplodedNode *Pred, const ReturnStmt *RS=nullptr)
Called by CoreEngine.
void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst, EvalCallOptions &Options)
void removeDeadOnEndOfFunction(ExplodedNode *Pred, ExplodedNodeSet &Dst)
Remove dead bindings/symbols before exiting a function.
void evalEagerlyAssumeBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, const Expr *Ex)
evalEagerlyAssumeBifurcation - Given the nodes in 'Src', eagerly assume concrete boolean values for '...
void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for ObjCAtSynchronizedStmts.
void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitReturnStmt - Transfer function logic for return statements.
SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, SVal LHS, SVal RHS, QualType T)
Definition ExprEngine.h:686
void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitLambdaExpr - Transfer function logic for LambdaExprs.
void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred)
void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitObjCForCollectionStmt - Transfer function logic for ObjCForCollectionStmt.
void VisitUnaryOperator(const UnaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitUnaryOperator - Transfer function logic for unary operators.
void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for computing the lvalue of an Objective-C ivar.
void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitDeclStmt - Transfer function logic for DeclStmts.
void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMSAsmStmt - Transfer function logic for MS inline asm.
void processStaticInitializer(const DeclStmt *DS, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF)
Called by CoreEngine.
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.
std::string DumpGraph(bool trim=false, StringRef Filename="")
Dump graph to the specified filename.
ProgramStateRef processRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef< const MemRegion * > ExplicitRegions, ArrayRef< const MemRegion * > Regions, const StackFrame *SF, const CallEvent *Call)
processRegionChanges - Called by ProgramStateManager whenever a change is made to the store.
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition ExprEngine.h:125
void printJson(raw_ostream &Out, ProgramStateRef State, const StackFrame *SF, const char *NL, unsigned int Space, bool IsDot) const
printJson - Called by ProgramStateManager to print checker-specific data.
void ProcessLifetimeEnd(const Stmt *S, const VarDecl *D, ExplodedNode *Pred)
static std::optional< unsigned > getPendingInitLoop(ProgramStateRef State, const CXXConstructExpr *E, const StackFrame *SF)
Retrieves the size of the array in the pending ArrayInitLoopExpr.
ProgramStateRef processAssume(ProgramStateRef state, SVal cond, bool assumption)
evalAssume - Callback function invoked by the ConstraintManager when making assumptions about state v...
AnalysisDeclContextManager & getAnalysisDeclContextManager()
Definition ExprEngine.h:219
static ProgramStateRef removeIterationState(ProgramStateRef State, const ObjCForCollectionStmt *O, const StackFrame *SF)
void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBlockExpr - Transfer function logic for BlockExprs.
void ProcessBaseDtor(const CFGBaseDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
static std::pair< const ProgramPointTag *, const ProgramPointTag * > getEagerlyAssumeBifurcationTags()
void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCall - Transfer function for function calls.
void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF)
Called by CoreEngine.
ProgramStateRef processRegionChange(ProgramStateRef state, const MemRegion *MR, const StackFrame *SF)
Definition ExprEngine.h:467
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition ExprEngine.h:214
StoreManager & getStoreManager()
Definition ExprEngine.h:480
void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Create a C++ temporary object for an rvalue.
void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGCCAsmStmt - Transfer function logic for inline asm.
BugReporter & getBugReporter()
Definition ExprEngine.h:230
void ProcessStmt(const Stmt *S, ExplodedNode *Pred)
ConstCFGElementRef getCFGElementRef() const
Definition ExprEngine.h:290
ExprEngine(cross_tu::CrossTranslationUnitContext &CTU, AnalysisManager &mgr, SetOfConstDecls *VisitedCalleesIn, FunctionSummariesTy *FS, InliningModes HowToInlineIn)
void ViewGraph(bool trim=false)
Visualize the ExplodedGraph created by executing the simulation.
ProgramStateRef notifyCheckersOfPointerEscape(ProgramStateRef State, const InvalidatedSymbols *Invalidated, ArrayRef< const MemRegion * > ExplicitRegions, const CallEvent *Call, RegionAndSymbolInvalidationTraits &ITraits)
Call PointerEscape callback when a value escapes as a result of region invalidation.
static const ProgramPointTag * cleanupNodeTag()
A tag to track convenience transitions, which can be removed at cleanup.
static ProgramStateRef setWhetherHasMoreIteration(ProgramStateRef State, const ObjCForCollectionStmt *O, const StackFrame *SF, bool HasMoreIteraton)
Note whether this loop has any more iterations to model. These methods.
static std::optional< unsigned > getPendingArrayDestruction(ProgramStateRef State, const StackFrame *SF)
Retrieves which element is being destructed in a non-POD type array.
ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State, ArrayRef< std::pair< SVal, SVal > > LocAndVals, const StackFrame *SF, PointerEscapeKind Kind, const CallEvent *Call)
Call PointerEscape callback when a value escapes as a result of bind.
void ConstructInitList(const Expr *Source, ArrayRef< Expr * > Args, bool IsTransparent, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
ProgramStateRef escapeValues(ProgramStateRef State, ArrayRef< SVal > Vs, PointerEscapeKind K, const CallEvent *Call=nullptr) const
A simple wrapper when you only need to notify checkers of pointer-escape of some values.
void ProcessLoopExit(const Stmt *S, ExplodedNode *Pred)
void processEndWorklist()
Called by CoreEngine when the analysis worklist has terminated.
CheckerManager & getCheckerManager() const
Definition ExprEngine.h:223
static std::optional< SVal > getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const StackFrame *SF)
By looking at a certain item that may be potentially part of an object's ConstructionContext,...
SymbolManager & getSymbolManager()
Definition ExprEngine.h:497
void processBeginOfFunction(ExplodedNode *Pred, ExplodedNodeSet &Dst, const BlockEdge &L)
Called by CoreEngine.
void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitAtomicExpr - Transfer function for builtin atomic expressions.
MemRegionManager & getRegionManager()
Definition ExprEngine.h:499
void ProcessMemberDtor(const CFGMemberDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitMemberExpr - Transfer function for member expressions.
ExplodedNode * processCFGBlockEntrance(const BlockEntrance &BE, ExplodedNode *Pred)
Called by CoreEngine when processing the entrance of a CFGBlock.
void processSwitch(const SwitchStmt *Switch, ExplodedNode *Pred, ExplodedNodeSet &Dst)
ProcessSwitch - Called by CoreEngine.
void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst)
static bool hasMoreIteration(ProgramStateRef State, const ObjCForCollectionStmt *O, const StackFrame *SF)
bool didEagerlyAssumeBifurcateAt(ProgramStateRef State, const Expr *Ex) const
ConstraintManager & getConstraintManager()
Definition ExprEngine.h:485
ProgramStateRef getInitialState(const StackFrame *InitSF)
getInitialState - Return the initial state used for the root vertex in the ExplodedGraph.
void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
unsigned getNumVisitedCurrent() const
Definition ExprEngine.h:299
void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitOffsetOfExpr - Transfer function for offsetof.
void evalLoad(ExplodedNodeSet &Dst, const Expr *NodeEx, const Expr *BoundExpr, ExplodedNode *Pred, ProgramStateRef St, SVal location, const ProgramPointTag *tag=nullptr, QualType LoadTy=QualType())
Simulate a read of the result of Ex.
void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Visit - Transfer function logic for all statements.
AnalysisManager & getAnalysisManager()
Definition ExprEngine.h:216
ExplodedGraph & getGraph()
Definition ExprEngine.h:325
void ProcessDeleteDtor(const CFGDeleteDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitCompoundLiteralExpr - Transfer function logic for compound literals.
SValBuilder & getSValBuilder()
Definition ExprEngine.h:227
void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitArrayInitLoopExpr - Transfer function for array init loop.
void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, const ProgramPointTag *tag=nullptr)
evalStore - Handle the semantics of a store via an assignment.
void VisitAttributedStmt(const AttributedStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitAttributedStmt - Transfer function logic for AttributedStmt.
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, ExplodedNodeSet &PreVisit, ExplodedNodeSet &Dst)
const StackFrame * getCurrStackFrame() const
Get the 'current' stack frame corresponding to the current work item (elementary analysis step handle...
Definition ExprEngine.h:280
const CFGBlock * getCurrBlock() const
Get the 'current' CFGBlock corresponding to the current work item (elementary analysis step handled b...
Definition ExprEngine.h:286
void processIndirectGoto(ExplodedNodeSet &Dst, const Expr *Tgt, const CFGBlock *Dispatch, ExplodedNode *Pred)
processIndirectGoto - Called by CoreEngine.
void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred)
static bool isLocType(QualType T)
Definition SVals.h:268
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemSpaceRegion * getMemorySpace(ProgramStateRef State) const
Returns the most specific memory space for this memory region in the given ProgramStateRef.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
MemSpaceRegion - A memory region that represents a "memory space"; for example, the set of global var...
Definition MemRegion.h:242
While alive, includes the current analysis stack in a crash trace.
Information about invalidation for a particular region/symbol.
Definition MemRegion.h:1663
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing '0' for the specified type.
NonLoc makeCompoundVal(QualType type, llvm::ImmutableList< SVal > vals)
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
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
bool isUndef() const
Definition SVals.h:113
bool isUnknownOrUndef() const
Definition SVals.h:115
bool isConstant() const
Definition SVals.cpp:245
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
bool isValid() const
Definition SVals.h:117
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
virtual SVal getLValueField(const FieldDecl *D, SVal Base)
Definition Store.h:153
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:480
A class responsible for cleaning up unused symbols.
void markLive(SymbolRef sym)
Unconditionally marks a symbol as live.
SymbolicRegion - A special, "non-concrete" region.
Definition MemRegion.h:813
Represents symbolic expression that isn't a location.
Definition SVals.h:285
Definition ARM.cpp:1102
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
@ PSK_DirectEscapeOnCall
The pointer has been passed to a function call directly.
@ PSK_EscapeOnBind
A pointer escapes due to binding its value to a location that the analyzer cannot track.
@ PSK_IndirectEscapeOnCall
The pointer has been passed to a function indirectly.
@ PSK_EscapeOther
The reason for pointer escape is unknown.
DefinedOrUnknownSVal getDynamicElementCount(ProgramStateRef State, const MemRegion *MR, SValBuilder &SVB, QualType Ty)
llvm::DenseSet< const Decl * > SetOfConstDecls
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition Store.h:50
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:133
ProgramStateRef processLoopEnd(const Stmt *LoopStmt, ProgramStateRef State)
Updates the given ProgramState.
bool isUnrolledState(ProgramStateRef State)
Returns if the given State indicates that is inside a completely unrolled loop.
ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState, const StackFrame *SF, unsigned BlockCount, ConstCFGElementRef Elem)
Get the states that result from widening the loop.
void markAllDynamicExtentLive(ProgramStateRef State, SymbolReaper &SymReaper)
ProgramStateRef updateLoopStack(const Stmt *LoopStmt, ASTContext &ASTCtx, ExplodedNode *Pred, unsigned maxVisitOnPath)
Updates the stack of loops contained by the ProgramState.
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1537
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition Specifiers.h:340
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:343
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6031
Expr * extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE)
Definition CFG.cpp:1461
@ CXXThis
Parameter for C++ 'this' argument.
Definition Decl.h:1762
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
Describes how types, statements, expressions, and declarations should be printed.
Hints for figuring out if a call should be inlined during evalCall().
Definition ExprEngine.h:93
bool IsTemporaryCtorOrDtor
This call is a constructor or a destructor of a temporary value.
Definition ExprEngine.h:103
bool IsArrayCtorOrDtor
This call is a constructor or a destructor for a single element within an array, a part of array cons...
Definition ExprEngine.h:100
Traits for storing the call processing policy inside GDM.
static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G)
static bool nodeHasBugReport(const ExplodedNode *N)
static bool traverseHiddenNodes(const ExplodedNode *N, llvm::function_ref< void(const ExplodedNode *)> PreCallback, llvm::function_ref< void(const ExplodedNode *)> PostCallback, llvm::function_ref< bool(const ExplodedNode *)> Stop)
PreCallback: callback before break.
static bool isNodeHidden(const ExplodedNode *N, const ExplodedGraph *G)