1 //===- ExprEngine.h - Path-Sensitive Expression-Level Dataflow --*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
16 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/Type.h"
20 #include "clang/Analysis/CFG.h"
21 #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h"
22 #include "clang/Analysis/ProgramPoint.h"
23 #include "clang/Basic/LLVM.h"
24 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
25 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
35 #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h"
36 #include "llvm/ADT/ArrayRef.h"
42 class AnalysisDeclContextManager;
43 class AnalyzerOptions;
45 class ConstructionContext;
46 class CXXBindTemporaryExpr;
48 class CXXConstructExpr;
56 class LocationContext;
57 class MaterializeTemporaryExpr;
60 class ObjCAtSynchronizedStmt;
61 class ObjCForCollectionStmt;
62 class ObjCIvarRefExpr;
63 class ObjCMessageExpr;
69 class CrossTranslationUnitContext;
71 } // namespace cross_tu
75 class BasicValueFactory;
78 class ConstraintManager;
79 class CXXTempObjectRegion;
81 class RegionAndSymbolInvalidationTraits;
84 class ExprEngine : public SubEngine {
86 /// The modes of inlining, which override the default analysis-wide settings.
88 /// Follow the default settings for inlining callees.
91 /// Do minimal inlining of callees.
95 /// Hints for figuring out of a call should be inlined during evalCall().
96 struct EvalCallOptions {
97 /// This call is a constructor or a destructor for which we do not currently
98 /// compute the this-region correctly.
99 bool IsCtorOrDtorWithImproperlyModeledTargetRegion = false;
101 /// This call is a constructor or a destructor for a single element within
102 /// an array, a part of array construction or destruction.
103 bool IsArrayCtorOrDtor = false;
105 /// This call is a constructor or a destructor of a temporary value.
106 bool IsTemporaryCtorOrDtor = false;
108 /// This call is a constructor for a temporary that is lifetime-extended
109 /// by binding it to a reference-type field within an aggregate,
110 /// for example 'A { const C &c; }; A a = { C() };'
111 bool IsTemporaryLifetimeExtendedViaAggregate = false;
117 cross_tu::CrossTranslationUnitContext &CTU;
119 AnalysisManager &AMgr;
121 AnalysisDeclContextManager &AnalysisDeclContexts;
125 /// G - the simulation graph.
128 /// StateMgr - Object that manages the data for all created states.
129 ProgramStateManager StateMgr;
131 /// SymMgr - Object that manages the symbol information.
132 SymbolManager &SymMgr;
134 /// MRMgr - MemRegionManager object that creates memory regions.
135 MemRegionManager &MRMgr;
137 /// svalBuilder - SValBuilder object that creates SVals from expressions.
138 SValBuilder &svalBuilder;
140 unsigned int currStmtIdx = 0;
141 const NodeBuilderContext *currBldrCtx = nullptr;
143 /// Helper object to determine if an Objective-C message expression
144 /// implicitly never returns.
145 ObjCNoReturn ObjCNoRet;
147 /// The BugReporter associated with this engine. It is important that
148 /// this object be placed at the very end of member variables so that its
149 /// destructor is called before the rest of the ExprEngine is destroyed.
150 PathSensitiveBugReporter BR;
152 /// The functions which have been analyzed through inlining. This is owned by
153 /// AnalysisConsumer. It can be null.
154 SetOfConstDecls *VisitedCallees;
156 /// The flag, which specifies the mode of inlining for the engine.
157 InliningModes HowToInline;
160 ExprEngine(cross_tu::CrossTranslationUnitContext &CTU, AnalysisManager &mgr,
161 SetOfConstDecls *VisitedCalleesIn,
162 FunctionSummariesTy *FS, InliningModes HowToInlineIn);
164 ~ExprEngine() override = default;
166 /// Returns true if there is still simulation state on the worklist.
167 bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) {
168 return Engine.ExecuteWorkList(L, Steps, nullptr);
171 /// Execute the work list with an initial state. Nodes that reaches the exit
172 /// of the function are added into the Dst set, which represent the exit
173 /// state of the function call. Returns true if there is still simulation
174 /// state on the worklist.
175 bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps,
176 ProgramStateRef InitState,
177 ExplodedNodeSet &Dst) {
178 return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
181 /// getContext - Return the ASTContext associated with this analysis.
182 ASTContext &getContext() const { return AMgr.getASTContext(); }
184 AnalysisManager &getAnalysisManager() override { return AMgr; }
186 AnalysisDeclContextManager &getAnalysisDeclContextManager() {
187 return AMgr.getAnalysisDeclContextManager();
190 CheckerManager &getCheckerManager() const {
191 return *AMgr.getCheckerManager();
194 SValBuilder &getSValBuilder() { return svalBuilder; }
196 BugReporter &getBugReporter() { return BR; }
198 cross_tu::CrossTranslationUnitContext *
199 getCrossTranslationUnitContext() override {
203 const NodeBuilderContext &getBuilderContext() {
208 const Stmt *getStmt() const;
210 void GenerateAutoTransition(ExplodedNode *N);
211 void enqueueEndOfPath(ExplodedNodeSet &S);
212 void GenerateCallExitNode(ExplodedNode *N);
215 /// Dump graph to the specified filename.
216 /// If filename is empty, generate a temporary one.
217 /// \return The filename the graph is written into.
218 std::string DumpGraph(bool trim = false, StringRef Filename="");
220 /// Dump the graph consisting of the given nodes to a specified filename.
221 /// Generate a temporary filename if it's not provided.
222 /// \return The filename the graph is written into.
223 std::string DumpGraph(ArrayRef<const ExplodedNode *> Nodes,
224 StringRef Filename = "");
226 /// Visualize the ExplodedGraph created by executing the simulation.
227 void ViewGraph(bool trim = false);
229 /// Visualize a trimmed ExplodedGraph that only contains paths to the given
231 void ViewGraph(ArrayRef<const ExplodedNode *> Nodes);
233 /// getInitialState - Return the initial state used for the root vertex
234 /// in the ExplodedGraph.
235 ProgramStateRef getInitialState(const LocationContext *InitLoc) override;
237 ExplodedGraph &getGraph() { return G; }
238 const ExplodedGraph &getGraph() const { return G; }
240 /// Run the analyzer's garbage collection - remove dead symbols and
241 /// bindings from the state.
243 /// Checkers can participate in this process with two callbacks:
244 /// \c checkLiveSymbols and \c checkDeadSymbols. See the CheckerDocumentation
245 /// class for more information.
247 /// \param Node The predecessor node, from which the processing should start.
248 /// \param Out The returned set of output nodes.
249 /// \param ReferenceStmt The statement which is about to be processed.
250 /// Everything needed for this statement should be considered live.
251 /// A null statement means that everything in child LocationContexts
253 /// \param LC The location context of the \p ReferenceStmt. A null location
254 /// context means that we have reached the end of analysis and that
255 /// all statements and local variables should be considered dead.
256 /// \param DiagnosticStmt Used as a location for any warnings that should
257 /// occur while removing the dead (e.g. leaks). By default, the
258 /// \p ReferenceStmt is used.
259 /// \param K Denotes whether this is a pre- or post-statement purge. This
260 /// must only be ProgramPoint::PostStmtPurgeDeadSymbolsKind if an
261 /// entire location context is being cleared, in which case the
262 /// \p ReferenceStmt must either be a ReturnStmt or \c NULL. Otherwise,
263 /// it must be ProgramPoint::PreStmtPurgeDeadSymbolsKind (the default)
264 /// and \p ReferenceStmt must be valid (non-null).
265 void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out,
266 const Stmt *ReferenceStmt, const LocationContext *LC,
267 const Stmt *DiagnosticStmt = nullptr,
268 ProgramPoint::Kind K = ProgramPoint::PreStmtPurgeDeadSymbolsKind);
270 /// processCFGElement - Called by CoreEngine. Used to generate new successor
271 /// nodes by processing the 'effects' of a CFG element.
272 void processCFGElement(const CFGElement E, ExplodedNode *Pred,
273 unsigned StmtIdx, NodeBuilderContext *Ctx) override;
275 void ProcessStmt(const Stmt *S, ExplodedNode *Pred);
277 void ProcessLoopExit(const Stmt* S, ExplodedNode *Pred);
279 void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred);
281 void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred);
283 void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred);
285 void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,
286 ExplodedNode *Pred, ExplodedNodeSet &Dst);
287 void ProcessDeleteDtor(const CFGDeleteDtor D,
288 ExplodedNode *Pred, ExplodedNodeSet &Dst);
289 void ProcessBaseDtor(const CFGBaseDtor D,
290 ExplodedNode *Pred, ExplodedNodeSet &Dst);
291 void ProcessMemberDtor(const CFGMemberDtor D,
292 ExplodedNode *Pred, ExplodedNodeSet &Dst);
293 void ProcessTemporaryDtor(const CFGTemporaryDtor D,
294 ExplodedNode *Pred, ExplodedNodeSet &Dst);
296 /// Called by CoreEngine when processing the entrance of a CFGBlock.
297 void processCFGBlockEntrance(const BlockEdge &L,
298 NodeBuilderWithSinks &nodeBuilder,
299 ExplodedNode *Pred) override;
301 /// ProcessBranch - Called by CoreEngine. Used to generate successor
302 /// nodes by processing the 'effects' of a branch condition.
303 void processBranch(const Stmt *Condition,
304 NodeBuilderContext& BuilderCtx,
306 ExplodedNodeSet &Dst,
307 const CFGBlock *DstT,
308 const CFGBlock *DstF) override;
310 /// Called by CoreEngine.
311 /// Used to generate successor nodes for temporary destructors depending
312 /// on whether the corresponding constructor was visited.
313 void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
314 NodeBuilderContext &BldCtx,
315 ExplodedNode *Pred, ExplodedNodeSet &Dst,
316 const CFGBlock *DstT,
317 const CFGBlock *DstF) override;
319 /// Called by CoreEngine. Used to processing branching behavior
320 /// at static initializers.
321 void processStaticInitializer(const DeclStmt *DS,
322 NodeBuilderContext& BuilderCtx,
324 ExplodedNodeSet &Dst,
325 const CFGBlock *DstT,
326 const CFGBlock *DstF) override;
328 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
329 /// nodes by processing the 'effects' of a computed goto jump.
330 void processIndirectGoto(IndirectGotoNodeBuilder& builder) override;
332 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
333 /// nodes by processing the 'effects' of a switch statement.
334 void processSwitch(SwitchNodeBuilder& builder) override;
336 /// Called by CoreEngine. Used to notify checkers that processing a
337 /// function has begun. Called for both inlined and and top-level functions.
338 void processBeginOfFunction(NodeBuilderContext &BC,
339 ExplodedNode *Pred, ExplodedNodeSet &Dst,
340 const BlockEdge &L) override;
342 /// Called by CoreEngine. Used to notify checkers that processing a
343 /// function has ended. Called for both inlined and and top-level functions.
344 void processEndOfFunction(NodeBuilderContext& BC,
346 const ReturnStmt *RS = nullptr) override;
348 /// Remove dead bindings/symbols before exiting a function.
349 void removeDeadOnEndOfFunction(NodeBuilderContext& BC,
351 ExplodedNodeSet &Dst);
353 /// Generate the entry node of the callee.
354 void processCallEnter(NodeBuilderContext& BC, CallEnter CE,
355 ExplodedNode *Pred) override;
357 /// Generate the sequence of nodes that simulate the call exit and the post
358 /// visit for CallExpr.
359 void processCallExit(ExplodedNode *Pred) override;
361 /// Called by CoreEngine when the analysis worklist has terminated.
362 void processEndWorklist() override;
364 /// evalAssume - Callback function invoked by the ConstraintManager when
365 /// making assumptions about state values.
366 ProgramStateRef processAssume(ProgramStateRef state, SVal cond,
367 bool assumption) override;
369 /// processRegionChanges - Called by ProgramStateManager whenever a change is made
370 /// to the store. Used to update checkers that track region values.
372 processRegionChanges(ProgramStateRef state,
373 const InvalidatedSymbols *invalidated,
374 ArrayRef<const MemRegion *> ExplicitRegions,
375 ArrayRef<const MemRegion *> Regions,
376 const LocationContext *LCtx,
377 const CallEvent *Call) override;
379 /// printJson - Called by ProgramStateManager to print checker-specific data.
380 void printJson(raw_ostream &Out, ProgramStateRef State,
381 const LocationContext *LCtx, const char *NL,
382 unsigned int Space, bool IsDot) const override;
384 ProgramStateManager &getStateManager() override { return StateMgr; }
386 StoreManager &getStoreManager() { return StateMgr.getStoreManager(); }
388 ConstraintManager &getConstraintManager() {
389 return StateMgr.getConstraintManager();
392 // FIXME: Remove when we migrate over to just using SValBuilder.
393 BasicValueFactory &getBasicVals() {
394 return StateMgr.getBasicVals();
397 SymbolManager &getSymbolManager() { return SymMgr; }
398 MemRegionManager &getRegionManager() { return MRMgr; }
400 NoteTag::Factory &getNoteTags() { return Engine.getNoteTags(); }
403 // Functions for external checking of whether we have unfinished work
404 bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }
405 bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); }
406 bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); }
408 const CoreEngine &getCoreEngine() const { return Engine; }
411 /// Visit - Transfer function logic for all statements. Dispatches to
412 /// other functions that handle specific kinds of statements.
413 void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
415 /// VisitArraySubscriptExpr - Transfer function for array accesses.
416 void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex,
418 ExplodedNodeSet &Dst);
420 /// VisitGCCAsmStmt - Transfer function logic for inline asm.
421 void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
422 ExplodedNodeSet &Dst);
424 /// VisitMSAsmStmt - Transfer function logic for MS inline asm.
425 void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
426 ExplodedNodeSet &Dst);
428 /// VisitBlockExpr - Transfer function logic for BlockExprs.
429 void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
430 ExplodedNodeSet &Dst);
432 /// VisitLambdaExpr - Transfer function logic for LambdaExprs.
433 void VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
434 ExplodedNodeSet &Dst);
436 /// VisitBinaryOperator - Transfer function logic for binary operators.
437 void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred,
438 ExplodedNodeSet &Dst);
441 /// VisitCall - Transfer function for function calls.
442 void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
443 ExplodedNodeSet &Dst);
445 /// VisitCast - Transfer function logic for all casts (implicit and explicit).
446 void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred,
447 ExplodedNodeSet &Dst);
449 /// VisitCompoundLiteralExpr - Transfer function logic for compound literals.
450 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
451 ExplodedNode *Pred, ExplodedNodeSet &Dst);
453 /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs.
454 void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D,
455 ExplodedNode *Pred, ExplodedNodeSet &Dst);
457 /// VisitDeclStmt - Transfer function logic for DeclStmts.
458 void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
459 ExplodedNodeSet &Dst);
461 /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose
462 void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R,
463 ExplodedNode *Pred, ExplodedNodeSet &Dst);
465 void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
466 ExplodedNodeSet &Dst);
468 /// VisitLogicalExpr - Transfer function logic for '&&', '||'
469 void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
470 ExplodedNodeSet &Dst);
472 /// VisitMemberExpr - Transfer function for member expressions.
473 void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
474 ExplodedNodeSet &Dst);
476 /// VisitAtomicExpr - Transfer function for builtin atomic expressions
477 void VisitAtomicExpr(const AtomicExpr *E, ExplodedNode *Pred,
478 ExplodedNodeSet &Dst);
480 /// Transfer function logic for ObjCAtSynchronizedStmts.
481 void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
482 ExplodedNode *Pred, ExplodedNodeSet &Dst);
484 /// Transfer function logic for computing the lvalue of an Objective-C ivar.
485 void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred,
486 ExplodedNodeSet &Dst);
488 /// VisitObjCForCollectionStmt - Transfer function logic for
489 /// ObjCForCollectionStmt.
490 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
491 ExplodedNode *Pred, ExplodedNodeSet &Dst);
493 void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred,
494 ExplodedNodeSet &Dst);
496 /// VisitReturnStmt - Transfer function logic for return statements.
497 void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred,
498 ExplodedNodeSet &Dst);
500 /// VisitOffsetOfExpr - Transfer function for offsetof.
501 void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred,
502 ExplodedNodeSet &Dst);
504 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof.
505 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
506 ExplodedNode *Pred, ExplodedNodeSet &Dst);
508 /// VisitUnaryOperator - Transfer function logic for unary operators.
509 void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,
510 ExplodedNodeSet &Dst);
512 /// Handle ++ and -- (both pre- and post-increment).
513 void VisitIncrementDecrementOperator(const UnaryOperator* U,
515 ExplodedNodeSet &Dst);
517 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
518 ExplodedNodeSet &PreVisit,
519 ExplodedNodeSet &Dst);
521 void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
522 ExplodedNodeSet &Dst);
524 void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
525 ExplodedNodeSet & Dst);
527 void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred,
528 ExplodedNodeSet &Dst);
530 void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest,
531 const Stmt *S, bool IsBaseDtor,
532 ExplodedNode *Pred, ExplodedNodeSet &Dst,
533 EvalCallOptions &Options);
535 void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
537 ExplodedNodeSet &Dst);
539 void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
540 ExplodedNodeSet &Dst);
542 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
543 ExplodedNodeSet &Dst);
545 /// Create a C++ temporary object for an rvalue.
546 void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
548 ExplodedNodeSet &Dst);
550 /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly assume symbolic
551 /// expressions of the form 'x != 0' and generate new nodes (stored in Dst)
552 /// with those assumptions.
553 void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
556 static std::pair<const ProgramPointTag *, const ProgramPointTag *>
557 geteagerlyAssumeBinOpBifurcationTags();
559 SVal evalMinus(SVal X) {
560 return X.isValid() ? svalBuilder.evalMinus(X.castAs<NonLoc>()) : X;
563 SVal evalComplement(SVal X) {
564 return X.isValid() ? svalBuilder.evalComplement(X.castAs<NonLoc>()) : X;
567 ProgramStateRef handleLValueBitCast(ProgramStateRef state, const Expr *Ex,
568 const LocationContext *LCtx, QualType T,
569 QualType ExTy, const CastExpr *CastE,
570 StmtNodeBuilder &Bldr,
573 ProgramStateRef handleLVectorSplat(ProgramStateRef state,
574 const LocationContext *LCtx,
575 const CastExpr *CastE,
576 StmtNodeBuilder &Bldr,
579 void handleUOExtension(ExplodedNodeSet::iterator I,
580 const UnaryOperator* U,
581 StmtNodeBuilder &Bldr);
584 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
585 NonLoc L, NonLoc R, QualType T) {
586 return svalBuilder.evalBinOpNN(state, op, L, R, T);
589 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
590 NonLoc L, SVal R, QualType T) {
591 return R.isValid() ? svalBuilder.evalBinOpNN(state, op, L,
592 R.castAs<NonLoc>(), T) : R;
595 SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op,
596 SVal LHS, SVal RHS, QualType T) {
597 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
600 /// By looking at a certain item that may be potentially part of an object's
601 /// ConstructionContext, retrieve such object's location. A particular
602 /// statement can be transparently passed as \p Item in most cases.
603 static Optional<SVal>
604 getObjectUnderConstruction(ProgramStateRef State,
605 const ConstructionContextItem &Item,
606 const LocationContext *LC);
609 /// evalBind - Handle the semantics of binding a value to a specific location.
610 /// This method is used by evalStore, VisitDeclStmt, and others.
611 void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred,
612 SVal location, SVal Val, bool atDeclInit = false,
613 const ProgramPoint *PP = nullptr);
615 /// Call PointerEscape callback when a value escapes as a result of bind.
616 ProgramStateRef processPointerEscapedOnBind(
617 ProgramStateRef State, ArrayRef<std::pair<SVal, SVal>> LocAndVals,
618 const LocationContext *LCtx, PointerEscapeKind Kind,
619 const CallEvent *Call) override;
622 processPointerEscapedOnBind(ProgramStateRef State,
624 const LocationContext *LCtx);
626 /// Call PointerEscape callback when a value escapes as a result of
627 /// region invalidation.
628 /// \param[in] ITraits Specifies invalidation traits for regions/symbols.
629 ProgramStateRef notifyCheckersOfPointerEscape(
630 ProgramStateRef State,
631 const InvalidatedSymbols *Invalidated,
632 ArrayRef<const MemRegion *> ExplicitRegions,
633 const CallEvent *Call,
634 RegionAndSymbolInvalidationTraits &ITraits) override;
636 /// A simple wrapper when you only need to notify checkers of pointer-escape
638 ProgramStateRef escapeValues(ProgramStateRef State, ArrayRef<SVal> Vs,
640 const CallEvent *Call = nullptr) const;
643 // FIXME: 'tag' should be removed, and a LocationContext should be used
645 // FIXME: Comment on the meaning of the arguments, when 'St' may not
646 // be the same as Pred->state, and when 'location' may not be the
647 // same as state->getLValue(Ex).
648 /// Simulate a read of the result of Ex.
649 void evalLoad(ExplodedNodeSet &Dst,
650 const Expr *NodeEx, /* Eventually will be a CFGStmt */
651 const Expr *BoundExpr,
655 const ProgramPointTag *tag = nullptr,
656 QualType LoadTy = QualType());
658 // FIXME: 'tag' should be removed, and a LocationContext should be used
660 void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE,
661 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val,
662 const ProgramPointTag *tag = nullptr);
664 /// Return the CFG element corresponding to the worklist element
665 /// that is currently being processed by ExprEngine.
666 CFGElement getCurrentCFGElement() {
667 return (*currBldrCtx->getBlock())[currStmtIdx];
670 /// Create a new state in which the call return value is binded to the
671 /// call origin expression.
672 ProgramStateRef bindReturnValue(const CallEvent &Call,
673 const LocationContext *LCtx,
674 ProgramStateRef State);
676 /// Evaluate a call, running pre- and post-call checkers and allowing checkers
677 /// to be responsible for handling the evaluation of the call itself.
678 void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred,
679 const CallEvent &Call);
681 /// Default implementation of call evaluation.
682 void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred,
683 const CallEvent &Call,
684 const EvalCallOptions &CallOpts = {});
687 ProgramStateRef finishArgumentConstruction(ProgramStateRef State,
688 const CallEvent &Call);
689 void finishArgumentConstruction(ExplodedNodeSet &Dst, ExplodedNode *Pred,
690 const CallEvent &Call);
692 void evalLoadCommon(ExplodedNodeSet &Dst,
693 const Expr *NodeEx, /* Eventually will be a CFGStmt */
698 const ProgramPointTag *tag,
701 void evalLocation(ExplodedNodeSet &Dst,
702 const Stmt *NodeEx, /* This will eventually be a CFGStmt */
709 /// Count the stack depth and determine if the call is recursive.
710 void examineStackFrames(const Decl *D, const LocationContext *LCtx,
711 bool &IsRecursive, unsigned &StackDepth);
713 enum CallInlinePolicy {
719 /// See if a particular call should be inlined, by only looking
720 /// at the call event and the current state of analysis.
721 CallInlinePolicy mayInlineCallKind(const CallEvent &Call,
722 const ExplodedNode *Pred,
723 AnalyzerOptions &Opts,
724 const EvalCallOptions &CallOpts);
726 /// See if the given AnalysisDeclContext is built for a function that we
727 /// should always inline simply because it's small enough.
728 /// Apart from "small" functions, we also have "large" functions
729 /// (cf. isLarge()), some of which are huge (cf. isHuge()), and we classify
730 /// the remaining functions as "medium".
731 bool isSmall(AnalysisDeclContext *ADC) const;
733 /// See if the given AnalysisDeclContext is built for a function that we
734 /// should inline carefully because it looks pretty large.
735 bool isLarge(AnalysisDeclContext *ADC) const;
737 /// See if the given AnalysisDeclContext is built for a function that we
738 /// should never inline because it's legit gigantic.
739 bool isHuge(AnalysisDeclContext *ADC) const;
741 /// See if the given AnalysisDeclContext is built for a function that we
742 /// should inline, just by looking at the declaration of the function.
743 bool mayInlineDecl(AnalysisDeclContext *ADC) const;
745 /// Checks our policies and decides weither the given call should be inlined.
746 bool shouldInlineCall(const CallEvent &Call, const Decl *D,
747 const ExplodedNode *Pred,
748 const EvalCallOptions &CallOpts = {});
750 bool inlineCall(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
751 ExplodedNode *Pred, ProgramStateRef State);
753 /// Conservatively evaluate call by invalidating regions and binding
754 /// a conjured return value.
755 void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr,
756 ExplodedNode *Pred, ProgramStateRef State);
758 /// Either inline or process the call conservatively (or both), based
759 /// on DynamicDispatchBifurcation data.
760 void BifurcateCall(const MemRegion *BifurReg,
761 const CallEvent &Call, const Decl *D, NodeBuilder &Bldr,
764 bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC);
766 /// Models a trivial copy or move constructor or trivial assignment operator
767 /// call with a simple bind.
768 void performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
769 const CallEvent &Call);
771 /// If the value of the given expression \p InitWithAdjustments is a NonLoc,
772 /// copy it into a new temporary object region, and replace the value of the
773 /// expression with that.
775 /// If \p Result is provided, the new region will be bound to this expression
776 /// instead of \p InitWithAdjustments.
778 /// Returns the temporary region with adjustments into the optional
779 /// OutRegionWithAdjustments out-parameter if a new region was indeed needed,
780 /// otherwise sets it to nullptr.
781 ProgramStateRef createTemporaryRegionIfNeeded(
782 ProgramStateRef State, const LocationContext *LC,
783 const Expr *InitWithAdjustments, const Expr *Result = nullptr,
784 const SubRegion **OutRegionWithAdjustments = nullptr);
786 /// Returns a region representing the first element of a (possibly
787 /// multi-dimensional) array, for the purposes of element construction or
790 /// On return, \p Ty will be set to the base type of the array.
792 /// If the type is not an array type at all, the original value is returned.
793 /// Otherwise the "IsArray" flag is set.
794 static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue,
795 QualType &Ty, bool &IsArray);
797 /// For a DeclStmt or CXXInitCtorInitializer, walk backward in the current CFG
798 /// block to find the constructor expression that directly constructed into
799 /// the storage for this statement. Returns null if the constructor for this
800 /// statement created a temporary object region rather than directly
801 /// constructing into an existing region.
802 const CXXConstructExpr *findDirectConstructorForCurrentCFGElement();
804 /// Update the program state with all the path-sensitive information
805 /// that's necessary to perform construction of an object with a given
806 /// syntactic construction context. If the construction context is unavailable
807 /// or unusable for any reason, a dummy temporary region is returned, and the
808 /// IsConstructorWithImproperlyModeledTargetRegion flag is set in \p CallOpts.
809 /// Returns the updated program state and the new object's this-region.
810 std::pair<ProgramStateRef, SVal> prepareForObjectConstruction(
811 const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
812 const ConstructionContext *CC, EvalCallOptions &CallOpts);
814 /// Store the location of a C++ object corresponding to a statement
815 /// until the statement is actually encountered. For example, if a DeclStmt
816 /// has CXXConstructExpr as its initializer, the object would be considered
817 /// to be "under construction" between CXXConstructExpr and DeclStmt.
818 /// This allows, among other things, to keep bindings to variable's fields
819 /// made within the constructor alive until its declaration actually
821 static ProgramStateRef
822 addObjectUnderConstruction(ProgramStateRef State,
823 const ConstructionContextItem &Item,
824 const LocationContext *LC, SVal V);
826 /// Mark the object sa fully constructed, cleaning up the state trait
827 /// that tracks objects under construction.
828 static ProgramStateRef
829 finishObjectConstruction(ProgramStateRef State,
830 const ConstructionContextItem &Item,
831 const LocationContext *LC);
833 /// If the given expression corresponds to a temporary that was used for
834 /// passing into an elidable copy/move constructor and that constructor
835 /// was actually elided, track that we also need to elide the destructor.
836 static ProgramStateRef elideDestructor(ProgramStateRef State,
837 const CXXBindTemporaryExpr *BTE,
838 const LocationContext *LC);
840 /// Stop tracking the destructor that corresponds to an elided constructor.
841 static ProgramStateRef
842 cleanupElidedDestructor(ProgramStateRef State,
843 const CXXBindTemporaryExpr *BTE,
844 const LocationContext *LC);
846 /// Returns true if the given expression corresponds to a temporary that
847 /// was constructed for passing into an elidable copy/move constructor
848 /// and that constructor was actually elided.
849 static bool isDestructorElided(ProgramStateRef State,
850 const CXXBindTemporaryExpr *BTE,
851 const LocationContext *LC);
853 /// Check if all objects under construction have been fully constructed
854 /// for the given context range (including FromLC, not including ToLC).
855 /// This is useful for assertions. Also checks if elided destructors
857 static bool areAllObjectsFullyConstructed(ProgramStateRef State,
858 const LocationContext *FromLC,
859 const LocationContext *ToLC);
862 /// Traits for storing the call processing policy inside GDM.
863 /// The GDM stores the corresponding CallExpr pointer.
864 // FIXME: This does not use the nice trait macros because it must be accessible
865 // from multiple translation units.
866 struct ReplayWithoutInlining{};
868 struct ProgramStateTrait<ReplayWithoutInlining> :
869 public ProgramStatePartialTrait<const void*> {
870 static void *GDMIndex();
877 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H