clang 24.0.0git
ExprEngine.h
Go to the documentation of this file.
1//===- ExprEngine.h - Path-Sensitive Expression-Level Dataflow --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines 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
15#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
16#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
17
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Analysis/CFG.h"
23#include "clang/Basic/LLVM.h"
37#include "llvm/ADT/ArrayRef.h"
38#include <cassert>
39#include <optional>
40#include <utility>
41
42namespace clang {
43
45class AnalyzerOptions;
46class ASTContext;
47class CFGBlock;
48class CFGElement;
51class CXXCatchStmt;
53class CXXDeleteExpr;
54class CXXNewExpr;
55class CXXThisExpr;
56class Decl;
57class DeclStmt;
58class GCCAsmStmt;
59class LambdaExpr;
61class MSAsmStmt;
62class NamedDecl;
65class ObjCIvarRefExpr;
66class ObjCMessageExpr;
67class ReturnStmt;
68class Stmt;
69
70namespace cross_tu {
71
73
74} // namespace cross_tu
75
76namespace ento {
77
78class AnalysisManager;
80class CallEvent;
81class CheckerManager;
83class ExplodedNodeSet;
84class ExplodedNode;
85class MemRegion;
86class ProgramState;
89class SymbolManager;
90
91/// Hints for figuring out if a call should be inlined during evalCall().
93 /// This call is a constructor or a destructor for which we do not currently
94 /// compute the this-region correctly.
96
97 /// This call is a constructor or a destructor for a single element within
98 /// an array, a part of array construction or destruction.
99 bool IsArrayCtorOrDtor = false;
100
101 /// This call is a constructor or a destructor of a temporary value.
103
104 /// This call is a constructor for a temporary that is lifetime-extended
105 /// by binding it to a reference-type field within an aggregate,
106 /// for example 'A { const C &c; }; A a = { C() };'
108
109 /// This call is a pre-C++17 elidable constructor that we failed to elide
110 /// because we failed to compute the target region into which
111 /// this constructor would have been ultimately elided. Analysis that
112 /// we perform in this case is still correct but it behaves differently,
113 /// as if copy elision is disabled.
115
117};
118
120 void anchor();
121
122public:
123 /// The modes of inlining, which override the default analysis-wide settings.
125 /// Follow the default settings for inlining callees.
127
128 /// Do minimal inlining of callees.
130 };
131
132private:
134 bool IsCTUEnabled;
135
136 AnalysisManager &AMgr;
137
138 AnalysisDeclContextManager &AnalysisDeclContexts;
139
140 CoreEngine Engine;
141
142 /// G - the simulation graph.
143 ExplodedGraph &G;
144
145 /// StateMgr - Object that manages the data for all created states.
146 ProgramStateManager StateMgr;
147
148 /// SymMgr - Object that manages the symbol information.
149 SymbolManager &SymMgr;
150
151 /// MRMgr - MemRegionManager object that creates memory regions.
152 MemRegionManager &MRMgr;
153
154 /// svalBuilder - SValBuilder object that creates SVals from expressions.
155 SValBuilder &svalBuilder;
156
157 unsigned int currStmtIdx = 0;
158 const StackFrame *CurrStackFrame = nullptr;
159 const CFGBlock *CurrBlock = nullptr;
160
161 /// Helper object to determine if an Objective-C message expression
162 /// implicitly never returns.
163 ObjCNoReturn ObjCNoRet;
164
165 /// The BugReporter associated with this engine. It is important that
166 /// this object be placed at the very end of member variables so that its
167 /// destructor is called before the rest of the ExprEngine is destroyed.
169
170 /// The functions which have been analyzed through inlining. This is owned by
171 /// AnalysisConsumer. It can be null.
172 SetOfConstDecls *VisitedCallees;
173
174 /// The flag, which specifies the mode of inlining for the engine.
175 InliningModes HowToInline;
176
177public:
179 SetOfConstDecls *VisitedCalleesIn,
180 FunctionSummariesTy *FS, InliningModes HowToInlineIn);
181
182 virtual ~ExprEngine() = default;
183
184 /// Returns true if there is still simulation state on the worklist.
185 bool ExecuteWorkList(const StackFrame *SF, unsigned Steps = 150000) {
186 assert(SF->inTopFrame());
187 BR.setAnalysisEntryPoint(SF->getDecl());
188 return Engine.ExecuteWorkList(SF, Steps, nullptr);
189 }
190
191 /// getContext - Return the ASTContext associated with this analysis.
192 ASTContext &getContext() const { return AMgr.getASTContext(); }
193
195 const AnalysisManager &getAnalysisManager() const { return AMgr; }
196
198 return AMgr.getAnalysisDeclContextManager();
199 }
200
202 return *AMgr.getCheckerManager();
203 }
204
205 SValBuilder &getSValBuilder() { return svalBuilder; }
206 const SValBuilder &getSValBuilder() const { return svalBuilder; }
207
208 BugReporter &getBugReporter() { return BR; }
209 const BugReporter &getBugReporter() const { return BR; }
210
213 return &CTU;
214 }
215
217 // The current StackFrame and Block is reset at the beginning of
218 // dispatchWorkItem. Ideally, this method should be called only once per
219 // dispatchWorkItem call (= elementary analysis step); so the following
220 // assertion is there to catch accidental repeated calls. If the current
221 // StackFrame and Block needs to change in the middle of a single step
222 // (which currently happens only once, in processCallExit), use an explicit
223 // call to resetCurrStackFrameAndBlock.
224 assert(!CurrBlock && !CurrStackFrame &&
225 "The current StackFrame and Block is already set");
226 assert(SF && B && "The StackFrame and Block must be non-null");
227 CurrStackFrame = SF;
228 CurrBlock = B;
229 }
230
232 CurrStackFrame = nullptr;
233 CurrBlock = nullptr;
234 }
235
237 assert(G.getRoot());
238 return G.getRoot()->getLocation().getStackFrame();
239 }
240
241 /// Get the 'current' stack frame corresponding to the current work item
242 /// (elementary analysis step handled by `dispatchWorkItem`).
243 /// FIXME: This sometimes (e.g. in some `BeginFunction` callbacks) differs
244 /// from the `StackFrame` that can be obtained from different sources
245 /// (e.g. a recent `ExplodedNode`). Traditionally this stack frame is
246 /// only used for block count calculations (`getNumVisited`); it is probably
247 /// wise to follow this tradition until the discrepancies are resolved.
248 const StackFrame *getCurrStackFrame() const { return CurrStackFrame; }
249
250 /// Get the 'current' CFGBlock corresponding to the current work item
251 /// (elementary analysis step handled by `dispatchWorkItem`).
252 const CFGBlock *getCurrBlock() const { return CurrBlock; }
253
255 return {getCurrBlock(), currStmtIdx};
256 }
257
258 unsigned getNumVisited(const StackFrame *SF, const CFGBlock *Block) const {
259 return Engine.WList->getBlockCounter().getNumVisited(SF,
260 Block->getBlockID());
261 }
262
263 unsigned getNumVisitedCurrent() const {
265 }
266
267 /// Dump graph to the specified filename.
268 /// If filename is empty, generate a temporary one.
269 /// \return The filename the graph is written into.
270 std::string DumpGraph(bool trim = false, StringRef Filename="");
271
272 /// Dump the graph consisting of the given nodes to a specified filename.
273 /// Generate a temporary filename if it's not provided.
274 /// \return The filename the graph is written into.
276 StringRef Filename = "");
277
278 /// Visualize the ExplodedGraph created by executing the simulation.
279 void ViewGraph(bool trim = false);
280
281 /// Visualize a trimmed ExplodedGraph that only contains paths to the given
282 /// nodes.
284
285 /// getInitialState - Return the initial state used for the root vertex
286 /// in the ExplodedGraph.
288
289 ExplodedGraph &getGraph() { return G; }
290 const ExplodedGraph &getGraph() const { return G; }
291
292 /// Run the analyzer's garbage collection - remove dead symbols and
293 /// bindings from the state.
294 ///
295 /// Checkers can participate in this process with two callbacks:
296 /// \c checkLiveSymbols and \c checkDeadSymbols. See the CheckerDocumentation
297 /// class for more information.
298 ///
299 /// \param Node The predecessor node, from which the processing should start.
300 /// \param Out The returned set of output nodes.
301 /// \param ReferenceStmt The statement which is about to be processed.
302 /// Everything needed for this statement should be considered live.
303 /// A null statement means that everything in child StackFrames
304 /// is dead.
305 /// \param SF The stack frame of the \p ReferenceStmt. A null stack frame
306 /// means that we have reached the end of analysis and that
307 /// all statements and local variables should be considered dead.
308 /// \param DiagnosticStmt Used as a location for any warnings that should
309 /// occur while removing the dead (e.g. leaks). By default, the
310 /// \p ReferenceStmt is used.
311 /// \param K Denotes whether this is a pre- or post-statement purge. This
312 /// must only be ProgramPoint::PostStmtPurgeDeadSymbolsKind if an
313 /// entire stack frame is being cleared, in which case the
314 /// \p ReferenceStmt must either be a ReturnStmt or \c NULL. Otherwise,
315 /// it must be ProgramPoint::PreStmtPurgeDeadSymbolsKind (the default)
316 /// and \p ReferenceStmt must be valid (non-null).
317 void
319 const Stmt *ReferenceStmt, const StackFrame *SF,
320 const Stmt *DiagnosticStmt = nullptr,
322
323 /// A tag to track convenience transitions, which can be removed at cleanup.
324 /// This tag applies to a node created after removeDead.
325 static const ProgramPointTag *cleanupNodeTag();
326
327 /// processCFGElement - Called by CoreEngine. Used to generate new successor
328 /// nodes by processing the 'effects' of a CFG element.
329 void processCFGElement(const CFGElement E, ExplodedNode *Pred,
330 unsigned StmtIdx);
331
332 void ProcessStmt(const Stmt *S, ExplodedNode *Pred);
333
334 void ProcessLoopExit(const Stmt* S, ExplodedNode *Pred);
335 void ProcessLifetimeEnd(const Stmt *S, const VarDecl *D, ExplodedNode *Pred);
336
338
340
341 void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred);
342
344 ExplodedNode *Pred, ExplodedNodeSet &Dst);
345 void ProcessDeleteDtor(const CFGDeleteDtor D,
346 ExplodedNode *Pred, ExplodedNodeSet &Dst);
347 void ProcessBaseDtor(const CFGBaseDtor D,
348 ExplodedNode *Pred, ExplodedNodeSet &Dst);
349 void ProcessMemberDtor(const CFGMemberDtor D,
350 ExplodedNode *Pred, ExplodedNodeSet &Dst);
352 ExplodedNode *Pred, ExplodedNodeSet &Dst);
353
354 /// Called by CoreEngine when processing the entrance of a CFGBlock.
355 /// Returns nullptr or a node descending from Pred.
357 ExplodedNode *Pred);
358
359 void runCheckersForBlockEntrance(const BlockEntrance &Entrance,
360 ExplodedNode *Pred, ExplodedNodeSet &Dst);
361
362 /// ProcessBranch - Called by CoreEngine. Used to generate successor nodes by
363 /// processing the 'effects' of a branch condition. If the branch condition
364 /// is a loop condition, IterationsCompletedInLoop is the number of completed
365 /// iterations (otherwise it's std::nullopt).
366 void processBranch(const Stmt *Condition, ExplodedNode *Pred,
367 ExplodedNodeSet &Dst, const CFGBlock *DstT,
368 const CFGBlock *DstF,
369 std::optional<unsigned> IterationsCompletedInLoop);
370
371 /// Called by CoreEngine.
372 /// Used to generate successor nodes for temporary destructors depending
373 /// on whether the corresponding constructor was visited.
375 ExplodedNode *Pred, ExplodedNodeSet &Dst,
376 const CFGBlock *DstT,
377 const CFGBlock *DstF);
378
379 /// Called by CoreEngine. Used to processing branching behavior
380 /// at static initializers.
382 ExplodedNodeSet &Dst, const CFGBlock *DstT,
383 const CFGBlock *DstF);
384
385 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
386 /// nodes by processing the 'effects' of a computed goto jump.
387 void processIndirectGoto(ExplodedNodeSet &Dst, const Expr *Tgt,
388 const CFGBlock *Dispatch, ExplodedNode *Pred);
389
390 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
391 /// nodes by processing the 'effects' of a switch statement.
392 void processSwitch(const SwitchStmt *Switch, ExplodedNode *Pred,
393 ExplodedNodeSet &Dst);
394
395 /// Called by CoreEngine. Used to notify checkers that processing a
396 /// function has begun. Called for both inlined and top-level functions.
398 const BlockEdge &L);
399
400 /// Called by CoreEngine. Used to notify checkers that processing a
401 /// function has ended. Called for both inlined and top-level functions.
402 void processEndOfFunction(ExplodedNode *Pred, const ReturnStmt *RS = nullptr);
403
404 /// Remove dead bindings/symbols before exiting a function.
406
407 /// Generate the entry node of the callee.
409
410 /// Generate the sequence of nodes that simulate the call exit and the post
411 /// visit for CallExpr.
412 void processCallExit(ExplodedNode *Pred);
413
414 /// Called by CoreEngine when the analysis worklist has terminated.
415 void processEndWorklist();
416
417 /// evalAssume - Callback function invoked by the ConstraintManager when
418 /// making assumptions about state values.
420 bool assumption);
421
422 /// processRegionChanges - Called by ProgramStateManager whenever a change is made
423 /// to the store. Used to update checkers that track region values.
426 const InvalidatedSymbols *invalidated,
427 ArrayRef<const MemRegion *> ExplicitRegions,
429 const StackFrame *SF, const CallEvent *Call);
430
432 const MemRegion *MR,
433 const StackFrame *SF) {
434 return processRegionChanges(state, nullptr, MR, MR, SF, nullptr);
435 }
436
437 /// printJson - Called by ProgramStateManager to print checker-specific data.
438 void printJson(raw_ostream &Out, ProgramStateRef State, const StackFrame *SF,
439 const char *NL, unsigned int Space, bool IsDot) const;
440
441 ProgramStateManager &getStateManager() { return StateMgr; }
442 const ProgramStateManager &getStateManager() const { return StateMgr; }
443
444 StoreManager &getStoreManager() { return StateMgr.getStoreManager(); }
446 return StateMgr.getStoreManager();
447 }
448
450 return StateMgr.getConstraintManager();
451 }
453 return StateMgr.getConstraintManager();
454 }
455
456 // FIXME: Remove when we migrate over to just using SValBuilder.
458 return StateMgr.getBasicVals();
459 }
460
461 SymbolManager &getSymbolManager() { return SymMgr; }
462 const SymbolManager &getSymbolManager() const { return SymMgr; }
464
465 DataTag::Factory &getDataTags() { return Engine.getDataTags(); }
466
467 // Functions for external checking of whether we have unfinished work.
468 bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
469 bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
470 bool hasExploredAllPaths() const { return Engine.hasExploredAllPaths(); }
471
472 const CoreEngine &getCoreEngine() const { return Engine; }
473
474public:
475 /// Visit - Transfer function logic for all statements. Dispatches to
476 /// other functions that handle specific kinds of statements.
477 void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
478
479 /// VisitArrayInitLoopExpr - Transfer function for array init loop.
481 ExplodedNodeSet &Dst);
482
483 /// VisitArraySubscriptExpr - Transfer function for array accesses.
485 ExplodedNode *Pred,
486 ExplodedNodeSet &Dst);
487
488 /// VisitGCCAsmStmt - Transfer function logic for inline asm.
489 void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
490 ExplodedNodeSet &Dst);
491
492 /// VisitMSAsmStmt - Transfer function logic for MS inline asm.
493 void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
494 ExplodedNodeSet &Dst);
495
496 /// VisitBlockExpr - Transfer function logic for BlockExprs.
497 void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
498 ExplodedNodeSet &Dst);
499
500 /// VisitLambdaExpr - Transfer function logic for LambdaExprs.
501 void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
502 ExplodedNodeSet &Dst);
503
504 /// VisitBinaryOperator - Transfer function logic for binary operators.
506 ExplodedNodeSet &Dst);
507
508
509 /// VisitCall - Transfer function for function calls.
510 void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
511 ExplodedNodeSet &Dst);
512
513 /// VisitCast - Transfer function logic for all casts (implicit and explicit).
514 void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
515 ExplodedNodeSet &Dst);
516
517 /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
519 ExplodedNode *Pred, ExplodedNodeSet &Dst);
520
521 /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
522 void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D,
523 ExplodedNode *Pred, ExplodedNodeSet &Dst);
524
525 /// VisitDeclStmt - Transfer function logic for DeclStmts.
526 void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
527 ExplodedNodeSet &Dst);
528
529 /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
530 void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R,
531 ExplodedNode *Pred, ExplodedNodeSet &Dst);
532
533 /// VisitAttributedStmt - Transfer function logic for AttributedStmt.
535 ExplodedNodeSet &Dst);
536
537 /// VisitLogicalExpr - Transfer function logic for '&&', '||'.
538 void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
539 ExplodedNodeSet &Dst);
540
541 /// VisitMemberExpr - Transfer function for member expressions.
542 void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
543 ExplodedNodeSet &Dst);
544
545 /// VisitAtomicExpr - Transfer function for builtin atomic expressions.
546 void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred,
547 ExplodedNodeSet &Dst);
548
549 /// Transfer function logic for ObjCAtSynchronizedStmts.
551 ExplodedNode *Pred, ExplodedNodeSet &Dst);
552
553 /// Transfer function logic for computing the lvalue of an Objective-C ivar.
555 ExplodedNodeSet &Dst);
556
557 /// VisitObjCForCollectionStmt - Transfer function logic for
558 /// ObjCForCollectionStmt.
560 ExplodedNode *Pred, ExplodedNodeSet &Dst);
561
562 /// Implementation detail of VisitObjCForCollectionStmt, which contains the
563 /// logic that needs to be executed both in the "container is empty" case
564 /// (HasElements=false) and the "container is not empty" case
565 /// (HasElements=true).
567 ExplodedNode *Pred, ExplodedNodeSet &Dst,
568 SVal ElementV, bool HasElements);
569
570 void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred,
571 ExplodedNodeSet &Dst);
572
573 /// VisitReturnStmt - Transfer function logic for return statements.
574 void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred,
575 ExplodedNodeSet &Dst);
576
577 /// VisitOffsetOfExpr - Transfer function for offsetof.
578 void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred,
579 ExplodedNodeSet &Dst);
580
581 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
583 ExplodedNode *Pred, ExplodedNodeSet &Dst);
584
585 /// VisitUnaryOperator - Transfer function logic for unary operators.
586 void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,
587 ExplodedNodeSet &Dst);
588
589 /// Handle ++ and -- (both pre- and post-increment).
591 ExplodedNode *Pred,
592 ExplodedNodeSet &Dst);
593
595 ExplodedNodeSet &PreVisit,
596 ExplodedNodeSet &Dst);
597
598 void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
599 ExplodedNodeSet &Dst);
600
601 void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
602 ExplodedNodeSet & Dst);
603
605 ExplodedNodeSet &Dst);
606
608 ExplodedNode *Pred, ExplodedNodeSet &Dst);
609
610 void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest,
611 const Stmt *S, bool IsBaseDtor,
612 ExplodedNode *Pred, ExplodedNodeSet &Dst,
613 EvalCallOptions &Options);
614
615 void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
616 ExplodedNode *Pred,
617 ExplodedNodeSet &Dst);
618
619 void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
620 ExplodedNodeSet &Dst);
621
623 ExplodedNodeSet &Dst);
624
625 /// Create a C++ temporary object for an rvalue.
627 ExplodedNode *Pred,
628 ExplodedNodeSet &Dst);
629
630 void ConstructInitList(const Expr *Source, ArrayRef<Expr *> Args,
631 bool IsTransparent, ExplodedNode *Pred,
632 ExplodedNodeSet &Dst);
633
634 /// evalEagerlyAssumeBifurcation - Given the nodes in 'Src', eagerly assume
635 /// concrete boolean values for 'Ex', storing the resulting nodes in 'Dst'.
637 const Expr *Ex);
638
639 bool didEagerlyAssumeBifurcateAt(ProgramStateRef State, const Expr *Ex) const;
640
641 static std::pair<const ProgramPointTag *, const ProgramPointTag *>
643
645 const StackFrame *SF, QualType T,
646 QualType ExTy, const CastExpr *CastE,
647 ExplodedNodeSet &Dst, ExplodedNode *Pred);
648
649public:
651 SVal LHS, SVal RHS, QualType T) {
652 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
653 }
654
655 /// Retrieves which element is being constructed in a non-POD type array.
656 static std::optional<unsigned>
658 const StackFrame *SF);
659
660 /// Retrieves which element is being destructed in a non-POD type array.
661 static std::optional<unsigned>
663
664 /// Retrieves the size of the array in the pending ArrayInitLoopExpr.
665 static std::optional<unsigned> getPendingInitLoop(ProgramStateRef State,
666 const CXXConstructExpr *E,
667 const StackFrame *SF);
668
669 /// By looking at a certain item that may be potentially part of an object's
670 /// ConstructionContext, retrieve such object's location. A particular
671 /// statement can be transparently passed as \p Item in most cases.
672 static std::optional<SVal>
674 const ConstructionContextItem &Item,
675 const StackFrame *SF);
676
677 /// Call PointerEscape callback when a value escapes as a result of bind.
679 ProgramStateRef State, ArrayRef<std::pair<SVal, SVal>> LocAndVals,
680 const StackFrame *SF, PointerEscapeKind Kind, const CallEvent *Call);
681
682 /// Call PointerEscape callback when a value escapes as a result of
683 /// region invalidation.
684 /// \param[in] ITraits Specifies invalidation traits for regions/symbols.
686 ProgramStateRef State,
687 const InvalidatedSymbols *Invalidated,
688 ArrayRef<const MemRegion *> ExplicitRegions,
689 const CallEvent *Call,
691
692private:
693 /// evalBind - Handle the semantics of binding a value to a specific location.
694 /// This method is used by evalStore, VisitDeclStmt, and others.
695 void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred,
696 SVal location, SVal Val, bool AtDeclInit = false,
697 const ProgramPoint *PP = nullptr);
698
700 SVal Val, const StackFrame *SF);
701
702public:
703 /// A simple wrapper when you only need to notify checkers of pointer-escape
704 /// of some values.
707 const CallEvent *Call = nullptr) const;
708
709 // FIXME: 'tag' should be removed, and a StackFrame should be used
710 // instead.
711 // FIXME: Comment on the meaning of the arguments, when 'St' may not
712 // be the same as Pred->state, and when 'location' may not be the
713 // same as state->getLValue(Ex).
714 /// Simulate a read of the result of Ex.
715 void evalLoad(ExplodedNodeSet &Dst,
716 const Expr *NodeEx, /* Eventually will be a CFGStmt */
717 const Expr *BoundExpr,
718 ExplodedNode *Pred,
720 SVal location,
721 const ProgramPointTag *tag = nullptr,
722 QualType LoadTy = QualType());
723
724 // FIXME: 'tag' should be removed, and a StackFrame should be used
725 // instead.
726 void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
727 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val,
728 const ProgramPointTag *tag = nullptr);
729
730 /// Return the CFG element corresponding to the worklist element
731 /// that is currently being processed by ExprEngine.
732 CFGElement getCurrentCFGElement() { return (*getCurrBlock())[currStmtIdx]; }
733
734 /// Create a new state in which the call return value is binded to the
735 /// call origin expression.
737 ProgramStateRef State);
738
739 /// Evaluate a call, running pre- and post-call checkers and allowing checkers
740 /// to be responsible for handling the evaluation of the call itself.
741 void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
742 const CallEvent &Call);
743
744 /// Default implementation of call evaluation.
746 const CallEvent &Call,
747 const EvalCallOptions &CallOpts = {});
748
749 /// Find location of the object that is being constructed by a given
750 /// constructor. This should ideally always succeed but due to not being
751 /// fully implemented it sometimes indicates that it failed via its
752 /// out-parameter CallOpts; in such cases a fake temporary region is
753 /// returned, which is better than nothing but does not represent
754 /// the actual behavior of the program. The Idx parameter is used if we
755 /// construct an array of objects. In that case it points to the index
756 /// of the continuous memory region.
757 /// E.g.:
758 /// For `int arr[4]` this index can be 0,1,2,3.
759 /// For `int arr2[3][3]` this index can be 0,1,...,7,8.
760 /// A multi-dimensional array is also a continuous memory location in a
761 /// row major order, so for arr[0][0] Idx is 0 and for arr[3][3] Idx is 8.
763 unsigned NumVisitedCaller,
764 const StackFrame *SF,
765 const ConstructionContext *CC,
766 EvalCallOptions &CallOpts,
767 unsigned Idx = 0);
768
769 /// Update the program state with all the path-sensitive information
770 /// that's necessary to perform construction of an object with a given
771 /// syntactic construction context. V and CallOpts have to be obtained from
772 /// computeObjectUnderConstruction() invoked with the same set of
773 /// the remaining arguments (E, State, SF, CC).
775 SVal V, const Expr *E, ProgramStateRef State, const StackFrame *SF,
776 const ConstructionContext *CC, const EvalCallOptions &CallOpts);
777
778 /// A convenient wrapper around computeObjectUnderConstruction
779 /// and updateObjectsUnderConstruction.
780 std::pair<ProgramStateRef, SVal>
782 const StackFrame *SF, const ConstructionContext *CC,
783 EvalCallOptions &CallOpts, unsigned Idx = 0) {
784
786 SF, CC, CallOpts, Idx);
787 State = updateObjectsUnderConstruction(V, E, State, SF, CC, CallOpts);
788
789 return std::make_pair(State, V);
790 }
791
792private:
793 ProgramStateRef finishArgumentConstruction(ProgramStateRef State,
794 const CallEvent &Call);
795 void finishArgumentConstruction(ExplodedNodeSet &Dst, ExplodedNode *Pred,
796 const CallEvent &Call);
797
798 void evalLocation(ExplodedNodeSet &Dst,
799 const Stmt *NodeEx, /* This will eventually be a CFGStmt */
800 const Stmt *BoundEx,
801 ExplodedNode *Pred,
803 SVal location,
804 bool isLoad);
805
806 /// Count the stack depth and determine if the call is recursive.
807 void
808 examineStackFrames(const Decl *D,
809 llvm::iterator_range<StackFrame::parent_iterator> Frames,
810 bool &IsRecursive, unsigned &StackDepth);
811
812 enum CallInlinePolicy {
813 CIP_Allowed,
814 CIP_DisallowedOnce,
815 CIP_DisallowedAlways
816 };
817
818 /// See if a particular call should be inlined, by only looking
819 /// at the call event and the current state of analysis.
820 CallInlinePolicy mayInlineCallKind(const CallEvent &Call,
821 const ExplodedNode *Pred,
822 AnalyzerOptions &Opts,
823 const EvalCallOptions &CallOpts);
824
825 /// See if the given AnalysisDeclContext is built for a function that we
826 /// should always inline simply because it's small enough.
827 /// Apart from "small" functions, we also have "large" functions
828 /// (cf. isLarge()), some of which are huge (cf. isHuge()), and we classify
829 /// the remaining functions as "medium".
830 bool isSmall(AnalysisDeclContext *ADC) const;
831
832 /// See if the given AnalysisDeclContext is built for a function that we
833 /// should inline carefully because it looks pretty large.
834 bool isLarge(AnalysisDeclContext *ADC) const;
835
836 /// See if the given AnalysisDeclContext is built for a function that we
837 /// should never inline because it's legit gigantic.
838 bool isHuge(AnalysisDeclContext *ADC) const;
839
840 /// See if the given AnalysisDeclContext is built for a function that we
841 /// should inline, just by looking at the declaration of the function.
842 bool mayInlineDecl(AnalysisDeclContext *ADC) const;
843
844 /// Checks our policies and decides whether the given call should be inlined.
845 bool shouldInlineCall(const CallEvent &Call, const Decl *D,
846 const ExplodedNode *Pred,
847 const EvalCallOptions &CallOpts = {});
848
849 /// Checks whether our policies allow us to inline a non-POD type array
850 /// construction.
851 bool shouldInlineArrayConstruction(const ProgramStateRef State,
852 const CXXConstructExpr *CE,
853 const StackFrame *SF);
854
855 /// Checks whether our policies allow us to inline a non-POD type array
856 /// destruction.
857 /// \param Size The size of the array.
858 bool shouldInlineArrayDestruction(uint64_t Size);
859
860 /// Prepares the program state for array destruction. If no error happens
861 /// the function binds a 'PendingArrayDestruction' entry to the state, which
862 /// it returns along with the index. If any error happens (we fail to read
863 /// the size, the index would be -1, etc.) the function will return the
864 /// original state along with an index of 0. The actual element count of the
865 /// array can be accessed by the optional 'ElementCountVal' parameter. \param
866 /// State The program state. \param Region The memory region where the array
867 /// is stored. \param ElementTy The type an element in the array. \param SF
868 /// The stack frame. \param ElementCountVal A pointer to an optional SVal.
869 /// If specified, the size of the array will be returned in it. It can
870 /// be Unknown.
871 std::pair<ProgramStateRef, uint64_t> prepareStateForArrayDestruction(
872 const ProgramStateRef State, const MemRegion *Region,
873 const QualType &ElementTy, const StackFrame *SF,
874 SVal *ElementCountVal = nullptr);
875
876 /// Checks whether we construct an array of non-POD type, and decides if the
877 /// constructor should be invoked once again.
878 bool shouldRepeatCtorCall(ProgramStateRef State, const CXXConstructExpr *E,
879 const StackFrame *SF);
880
881 void inlineCall(WorkList *WList, const CallEvent &Call, const Decl *D,
882 ExplodedNode *Pred, ProgramStateRef State);
883
884 void ctuBifurcate(const CallEvent &Call, const Decl *D, ExplodedNodeSet &Dst,
885 ExplodedNode *Pred, ProgramStateRef State);
886
887 /// Returns true if the CTU analysis is running its second phase.
888 bool isSecondPhaseCTU() { return IsCTUEnabled && !Engine.getCTUWorkList(); }
889
890 /// Conservatively evaluate call by invalidating regions and binding
891 /// a conjured return value.
892 ExplodedNode *conservativeEvalCall(const CallEvent &Call, ExplodedNode *Pred,
893 ProgramStateRef State);
894
895 /// Either inline or process the call conservatively (or both), based
896 /// on DynamicDispatchBifurcation data.
897 void dynDispatchBifurcate(const MemRegion *BifurReg, const CallEvent &Call,
898 const Decl *D, ExplodedNodeSet &Dst,
899 ExplodedNode *Pred);
900
901 bool replayWithoutInlining(ExplodedNode *P, const StackFrame *CalleeSF);
902
903 /// Models a trivial copy or move constructor or trivial assignment operator
904 /// call with a simple bind.
905 void performTrivialCopy(ExplodedNodeSet &Dst, ExplodedNode *Pred,
906 const CallEvent &Call);
907
908 /// If the value of the given expression \p InitWithAdjustments is a NonLoc,
909 /// copy it into a new temporary object region, and replace the value of the
910 /// expression with that.
911 ///
912 /// If \p Result is provided, the new region will be bound to this expression
913 /// instead of \p InitWithAdjustments.
914 ///
915 /// Returns the temporary region with adjustments into the optional
916 /// OutRegionWithAdjustments out-parameter if a new region was indeed needed,
917 /// otherwise sets it to nullptr.
918 ProgramStateRef createTemporaryRegionIfNeeded(
919 ProgramStateRef State, const StackFrame *SF,
920 const Expr *InitWithAdjustments, const Expr *Result = nullptr,
921 const SubRegion **OutRegionWithAdjustments = nullptr);
922
923 /// Returns a region representing the `Idx`th element of a (possibly
924 /// multi-dimensional) array, for the purposes of element construction or
925 /// destruction.
926 ///
927 /// On return, \p Ty will be set to the base type of the array.
928 ///
929 /// If the type is not an array type at all, the original value is returned.
930 /// Otherwise the "IsArray" flag is set.
931 static SVal makeElementRegion(ProgramStateRef State, SVal LValue,
932 QualType &Ty, bool &IsArray, unsigned Idx = 0);
933
934 /// Common code that handles either a CXXConstructExpr or a
935 /// CXXInheritedCtorInitExpr.
936 void handleConstructor(const Expr *E, ExplodedNode *Pred,
937 ExplodedNodeSet &Dst);
938
939public:
940 /// Note whether this loop has any more iterations to model. These methods
941 // are essentially an interface for a GDM trait. Further reading in
942 /// ExprEngine::VisitObjCForCollectionStmt().
943 [[nodiscard]] static ProgramStateRef
945 const ObjCForCollectionStmt *O,
946 const StackFrame *SF, bool HasMoreIteraton);
947
948 [[nodiscard]] static ProgramStateRef
949 removeIterationState(ProgramStateRef State, const ObjCForCollectionStmt *O,
950 const StackFrame *SF);
951
952 [[nodiscard]] static bool hasMoreIteration(ProgramStateRef State,
953 const ObjCForCollectionStmt *O,
954 const StackFrame *SF);
955
956private:
957 /// Assuming we construct an array of non-POD types, this method allows us
958 /// to store which element is to be constructed next.
959 static ProgramStateRef setIndexOfElementToConstruct(ProgramStateRef State,
960 const CXXConstructExpr *E,
961 const StackFrame *SF,
962 unsigned Idx);
963
964 static ProgramStateRef removeIndexOfElementToConstruct(
965 ProgramStateRef State, const CXXConstructExpr *E, const StackFrame *SF);
966
967 /// Assuming we destruct an array of non-POD types, this method allows us
968 /// to store which element is to be destructed next.
969 static ProgramStateRef setPendingArrayDestruction(ProgramStateRef State,
970 const StackFrame *SF,
971 unsigned Idx);
972
973 static ProgramStateRef removePendingArrayDestruction(ProgramStateRef State,
974 const StackFrame *SF);
975
976 /// Sets the size of the array in a pending ArrayInitLoopExpr.
977 static ProgramStateRef setPendingInitLoop(ProgramStateRef State,
978 const CXXConstructExpr *E,
979 const StackFrame *SF, unsigned Idx);
980
981 static ProgramStateRef removePendingInitLoop(ProgramStateRef State,
982 const CXXConstructExpr *E,
983 const StackFrame *SF);
984
985 static ProgramStateRef removeStateTraitsUsedForArrayEvaluation(
986 ProgramStateRef State, const CXXConstructExpr *E, const StackFrame *SF);
987
988 /// Store the location of a C++ object corresponding to a statement
989 /// until the statement is actually encountered. For example, if a DeclStmt
990 /// has CXXConstructExpr as its initializer, the object would be considered
991 /// to be "under construction" between CXXConstructExpr and DeclStmt.
992 /// This allows, among other things, to keep bindings to variable's fields
993 /// made within the constructor alive until its declaration actually
994 /// goes into scope.
995 static ProgramStateRef
996 addObjectUnderConstruction(ProgramStateRef State,
997 const ConstructionContextItem &Item,
998 const StackFrame *SF, SVal V);
999
1000 /// Mark the object as fully constructed, cleaning up the state trait
1001 /// that tracks objects under construction.
1002 static ProgramStateRef
1003 finishObjectConstruction(ProgramStateRef State,
1004 const ConstructionContextItem &Item,
1005 const StackFrame *SF);
1006
1007 /// If the given expression corresponds to a temporary that was used for
1008 /// passing into an elidable copy/move constructor and that constructor
1009 /// was actually elided, track that we also need to elide the destructor.
1010 static ProgramStateRef elideDestructor(ProgramStateRef State,
1011 const CXXBindTemporaryExpr *BTE,
1012 const StackFrame *SF);
1013
1014 /// Stop tracking the destructor that corresponds to an elided constructor.
1015 static ProgramStateRef
1016 cleanupElidedDestructor(ProgramStateRef State,
1017 const CXXBindTemporaryExpr *BTE,
1018 const StackFrame *SF);
1019
1020 /// Returns true if the given expression corresponds to a temporary that
1021 /// was constructed for passing into an elidable copy/move constructor
1022 /// and that constructor was actually elided.
1023 static bool isDestructorElided(ProgramStateRef State,
1024 const CXXBindTemporaryExpr *BTE,
1025 const StackFrame *SF);
1026
1027 /// Check if all objects under construction have been fully constructed
1028 /// for the given context range (including FromSF, not including ToSF).
1029 /// This is useful for assertions. Also checks if elided destructors
1030 /// were cleaned up.
1031 static bool areAllObjectsFullyConstructed(ProgramStateRef State,
1032 const StackFrame *FromSF,
1033 const StackFrame *ToSF);
1034};
1035
1036/// Traits for storing the call processing policy inside GDM.
1037/// The GDM stores the corresponding CallExpr pointer.
1038// FIXME: This does not use the nice trait macros because it must be accessible
1039// from multiple translation units.
1041template <>
1043 public ProgramStatePartialTrait<const void*> {
1044 static void *GDMIndex();
1045};
1046
1047} // namespace ento
1048
1049} // namespace clang
1050
1051#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
#define V(N, I)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
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
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Stores options for the analyzer from the command line.
Represents a loop initializing the elements of an array.
Definition Expr.h:6018
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2765
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6978
Represents an attribute applied to a statement.
Definition Stmt.h:2215
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
BinaryOperatorKind Opcode
Definition Expr.h:4087
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
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
Represents a single basic block in a source-level CFG.
Definition CFG.h:652
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
Represents C++ object destructor implicitly generated by compiler on various occasions.
Definition CFG.h:414
Represents C++ base or member initializer from constructor's initialization list.
Definition CFG.h:232
Represents C++ object destructor implicitly generated for member object in destructor.
Definition CFG.h:537
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition CFG.h:558
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1755
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
Represents the this expression in C++.
Definition ExprCXX.h:1158
Represents a point when we begin processing an inlined call.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3720
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3649
Represents a single point (AST node) in the program that requires attention during construction of an...
ConstructionContext's subclasses describe different ways of constructing an object in C++.
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:113
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3458
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
This represents a Microsoft inline-assembly statement extension.
Definition Stmt.h:3677
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4973
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
This represents a decl that may have a name.
Definition Decl.h:275
Represents Objective-C's @synchronized statement.
Definition StmtObjC.h:303
Represents Objective-C's collection statement.
Definition StmtObjC.h:23
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:581
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:972
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2571
ProgramPoints can be "tagged" as representing points specific to a given analysis entity.
A (possibly-)qualified type.
Definition TypeBase.h:938
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3172
It represents a stack frame of the call stack.
const Decl * getDecl() const
Stmt - This represents one statement.
Definition Stmt.h:85
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2521
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2669
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
Represents a variable declaration or definition.
Definition Decl.h:933
This class is used for tools that requires cross translation unit capability.
BugReporter is a utility class for generating PathDiagnostics for analysis.
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:152
CoreEngine - Implements the core logic of the graph-reachability analysis.
Definition CoreEngine.h:50
WorkList * getCTUWorkList() const
Definition CoreEngine.h:166
ExplodedNodeSet is a set of ExplodedNode * elements with the invariant that its elements cannot be nu...
void VisitBinaryOperator(const BinaryOperator *B, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitBinaryOperator - Transfer function logic for binary operators.
const StackFrame * getRootStackFrame() const
Definition ExprEngine.h:236
ProgramStateManager & getStateManager()
Definition ExprEngine.h:441
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)
bool hasExploredAllPaths() const
Definition ExprEngine.h:470
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)
ProgramStateRef handleLValueBitCast(ProgramStateRef state, const Expr *Ex, const StackFrame *SF, QualType T, QualType ExTy, const CastExpr *CastE, ExplodedNodeSet &Dst, ExplodedNode *Pred)
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:457
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.
const CoreEngine & getCoreEngine() const
Definition ExprEngine.h:472
SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, SVal LHS, SVal RHS, QualType T)
Definition ExprEngine.h:650
void processCallEnter(CallEnter CE, ExplodedNode *Pred)
Generate the entry node of the callee.
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 processCallExit(ExplodedNode *Pred)
Generate the sequence of nodes that simulate the call exit and the post visit for CallExpr.
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.
const SymbolManager & getSymbolManager() const
Definition ExprEngine.h:462
CFGElement getCurrentCFGElement()
Return the CFG element corresponding to the worklist element that is currently being processed by Exp...
Definition ExprEngine.h:732
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.
virtual ~ExprEngine()=default
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:124
@ Inline_Minimal
Do minimal inlining of callees.
Definition ExprEngine.h:129
@ Inline_Regular
Follow the default settings for inlining callees.
Definition ExprEngine.h:126
ProgramStateRef bindReturnValue(const CallEvent &Call, const StackFrame *SF, ProgramStateRef State)
Create a new state in which the call return value is binded to the call origin expression.
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.
const ExplodedGraph & getGraph() const
Definition ExprEngine.h:290
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.
const StoreManager & getStoreManager() const
Definition ExprEngine.h:445
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:197
const ProgramStateManager & getStateManager() const
Definition ExprEngine.h:442
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 VisitIncrementDecrementOperator(const UnaryOperator *U, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Handle ++ and – (both pre- and post-increment).
void setCurrStackFrameAndBlock(const StackFrame *SF, const CFGBlock *B)
Definition ExprEngine.h:216
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:431
ASTContext & getContext() const
getContext - Return the ASTContext associated with this analysis.
Definition ExprEngine.h:192
StoreManager & getStoreManager()
Definition ExprEngine.h:444
const ConstraintManager & getConstraintManager() const
Definition ExprEngine.h:452
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 evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, const CallEvent &Call)
Evaluate a call, running pre- and post-call checkers and allowing checkers to be responsible for hand...
void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitGCCAsmStmt - Transfer function logic for inline asm.
BugReporter & getBugReporter()
Definition ExprEngine.h:208
bool hasEmptyWorkList() const
Definition ExprEngine.h:469
bool ExecuteWorkList(const StackFrame *SF, unsigned Steps=150000)
Returns true if there is still simulation state on the worklist.
Definition ExprEngine.h:185
ProgramStateRef updateObjectsUnderConstruction(SVal V, const Expr *E, ProgramStateRef State, const StackFrame *SF, const ConstructionContext *CC, const EvalCallOptions &CallOpts)
Update the program state with all the path-sensitive information that's necessary to perform construc...
void ProcessStmt(const Stmt *S, ExplodedNode *Pred)
void defaultEvalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, const CallEvent &Call, const EvalCallOptions &CallOpts={})
Default implementation of call evaluation.
ConstCFGElementRef getCFGElementRef() const
Definition ExprEngine.h:254
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.
void populateObjCForDestinationSet(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst, SVal ElementV, bool HasElements)
Implementation detail of VisitObjCForCollectionStmt, which contains the logic that needs to be execut...
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.
cross_tu::CrossTranslationUnitContext * getCrossTranslationUnitContext()
Definition ExprEngine.h:212
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.
std::pair< ProgramStateRef, SVal > handleConstructionContext(const Expr *E, ProgramStateRef State, const StackFrame *SF, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
A convenient wrapper around computeObjectUnderConstruction and updateObjectsUnderConstruction.
Definition ExprEngine.h:781
void ProcessLoopExit(const Stmt *S, ExplodedNode *Pred)
void processEndWorklist()
Called by CoreEngine when the analysis worklist has terminated.
CheckerManager & getCheckerManager() const
Definition ExprEngine.h:201
static std::optional< SVal > getObjectUnderConstruction(ProgramStateRef State, const ConstructionContextItem &Item, const StackFrame *SF)
By looking at a certain item that may be potentially part of an object's ConstructionContext,...
SymbolManager & getSymbolManager()
Definition ExprEngine.h:461
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.
bool wasBlocksExhausted() const
Definition ExprEngine.h:468
MemRegionManager & getRegionManager()
Definition ExprEngine.h:463
const AnalysisManager & getAnalysisManager() const
Definition ExprEngine.h:195
SVal computeObjectUnderConstruction(const Expr *E, ProgramStateRef State, unsigned NumVisitedCaller, const StackFrame *SF, const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx=0)
Find location of the object that is being constructed by a given constructor.
void 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:449
DataTag::Factory & getDataTags()
Definition ExprEngine.h:465
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:263
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:194
ExplodedGraph & getGraph()
Definition ExprEngine.h:289
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.
const BugReporter & getBugReporter() const
Definition ExprEngine.h:209
SValBuilder & getSValBuilder()
Definition ExprEngine.h:205
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:248
const CFGBlock * getCurrBlock() const
Get the 'current' CFGBlock corresponding to the current work item (elementary analysis step handled b...
Definition ExprEngine.h:252
const SValBuilder & getSValBuilder() const
Definition ExprEngine.h:206
unsigned getNumVisited(const StackFrame *SF, const CFGBlock *Block) const
Definition ExprEngine.h:258
void processIndirectGoto(ExplodedNodeSet &Dst, const Expr *Tgt, const CFGBlock *Dispatch, ExplodedNode *Pred)
processIndirectGoto - Called by CoreEngine.
void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred)
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
GRBugReporter is used for generating path-sensitive reports.
ProgramState - This class encapsulates:
Information about invalidation for a particular region/symbol.
Definition MemRegion.h:1663
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
Definition ARM.cpp:1102
Definition SPIR.cpp:35
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
llvm::DenseSet< const Decl * > SetOfConstDecls
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition Store.h:50
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Top level wrappers for InstallAPI frontend operations.
CFGBlock::ConstCFGElementRef ConstCFGElementRef
Definition CFG.h:1248
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
Hints for figuring out if a call should be inlined during evalCall().
Definition ExprEngine.h:92
bool IsTemporaryLifetimeExtendedViaAggregate
This call is a constructor for a temporary that is lifetime-extended by binding it to a reference-typ...
Definition ExprEngine.h:107
bool IsTemporaryCtorOrDtor
This call is a constructor or a destructor of a temporary value.
Definition ExprEngine.h:102
bool IsArrayCtorOrDtor
This call is a constructor or a destructor for a single element within an array, a part of array cons...
Definition ExprEngine.h:99
bool IsElidableCtorThatHasNotBeenElided
This call is a pre-C++17 elidable constructor that we failed to elide because we failed to compute th...
Definition ExprEngine.h:114
bool IsCtorOrDtorWithImproperlyModeledTargetRegion
This call is a constructor or a destructor for which we do not currently compute the this-region corr...
Definition ExprEngine.h:95
Traits for storing the call processing policy inside GDM.