clang 24.0.0git
ExplodedGraph.cpp
Go to the documentation of this file.
1//===- ExplodedGraph.cpp - Local, Path-Sens. "Exploded Graph" -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the template classes ExplodedNode and ExplodedGraph,
10// which represent a path-sensitive, intra-procedural "exploded graph."
11//
12//===----------------------------------------------------------------------===//
13
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprObjC.h"
17#include "clang/AST/ParentMap.h"
18#include "clang/AST/Stmt.h"
21#include "clang/Basic/LLVM.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/FoldingSet.h"
27#include "llvm/ADT/PointerUnion.h"
28#include <cassert>
29#include <memory>
30#include <optional>
31
32using namespace clang;
33using namespace ento;
34
35//===----------------------------------------------------------------------===//
36// Cleanup.
37//===----------------------------------------------------------------------===//
38
40
42
43//===----------------------------------------------------------------------===//
44// Node reclamation.
45//===----------------------------------------------------------------------===//
46
52
53bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
54 // First, we only consider nodes for reclamation of the following
55 // conditions apply:
56 //
57 // (1) 1 predecessor (that has one successor)
58 // (2) 1 successor (that has one predecessor)
59 //
60 // If a node has no successor it is on the "frontier", while a node
61 // with no predecessor is a root.
62 //
63 // After these prerequisites, we discard all "filler" nodes that
64 // are used only for intermediate processing, and are not essential
65 // for analyzer history:
66 //
67 // (a) PreStmtPurgeDeadSymbols
68 //
69 // We then discard all other nodes where *all* of the following conditions
70 // apply:
71 //
72 // (3) The ProgramPoint is for a PostStmt, but not a PostStore.
73 // (4) There is no 'tag' for the ProgramPoint.
74 // (5) The 'store' is the same as the predecessor.
75 // (6) The 'GDM' is the same as the predecessor.
76 // (7) The StackFrame is the same as the predecessor.
77 // (8) Expressions that are *not* lvalue expressions.
78 // (9) The PostStmt isn't for a non-consumed Stmt or Expr.
79 // (10) The successor is neither a CallExpr StmtPoint nor a CallEnter or
80 // PreImplicitCall (so that we would be able to find it when retrying a
81 // call with no inlining).
82 // FIXME: It may be safe to reclaim PreCall and PostCall nodes as well.
83
84 // Conditions 1 and 2.
85 if (node->pred_size() != 1 || node->succ_size() != 1)
86 return false;
87
88 const ExplodedNode *pred = *(node->pred_begin());
89 if (pred->succ_size() != 1)
90 return false;
91
92 const ExplodedNode *succ = *(node->succ_begin());
93 if (succ->pred_size() != 1)
94 return false;
95
96 // Now reclaim any nodes that are (by definition) not essential to
97 // analysis history and are not consulted by any client code.
98 ProgramPoint progPoint = node->getLocation();
99 if (progPoint.getAs<PreStmtPurgeDeadSymbols>())
100 return !progPoint.getTag();
101
102 // Condition 3.
103 if (!progPoint.getAs<PostStmt>() || progPoint.getAs<PostStore>())
104 return false;
105
106 // Condition 4.
107 if (progPoint.getTag())
108 return false;
109
110 // Conditions 5, 6, and 7.
111 const ProgramState *state = node->getState().get();
112 const ProgramState *pred_state = pred->getState().get();
113 if (state->store != pred_state->store || state->GDM != pred_state->GDM ||
114 progPoint.getStackFrame() != pred->getStackFrame())
115 return false;
116
117 // All further checks require expressions. As per #3, we know that we have
118 // a PostStmt.
119 const Expr *Ex = dyn_cast<Expr>(progPoint.castAs<PostStmt>().getStmt());
120 if (!Ex)
121 return false;
122
123 // Condition 8.
124 // Do not collect nodes for "interesting" lvalue expressions since they are
125 // used extensively for generating path diagnostics.
127 return false;
128
129 // Condition 9.
130 // Do not collect nodes for non-consumed Stmt or Expr to ensure precise
131 // diagnostic generation; specifically, so that we could anchor arrows
132 // pointing to the beginning of statements (as written in code).
133 const ParentMap &PM = progPoint.getStackFrame()->getParentMap();
134 if (!PM.isConsumedExpr(Ex))
135 return false;
136
137 // Condition 10.
138 const ProgramPoint SuccLoc = succ->getLocation();
139 if (std::optional<StmtPoint> SP = SuccLoc.getAs<StmtPoint>())
140 if (CallEvent::isCallStmt(SP->getStmt()))
141 return false;
142
143 // Condition 10, continuation.
144 if (SuccLoc.getAs<CallEnter>() || SuccLoc.getAs<PreImplicitCall>())
145 return false;
146
147 return true;
148}
149
151 EndNodes.push_back(V);
152 return V;
153}
154
155void ExplodedGraph::collectNode(ExplodedNode *node) {
156 // Removing a node means:
157 // (a) changing the predecessors successor to the successor of this node
158 // (b) changing the successors predecessor to the predecessor of this node
159 // (c) Putting 'node' onto freeNodes.
160 assert(node->pred_size() == 1 || node->succ_size() == 1);
161 ExplodedNode *pred = *(node->pred_begin());
162 ExplodedNode *succ = *(node->succ_begin());
163 pred->replaceSuccessor(succ);
164 succ->replacePredecessor(pred);
165 FreeNodes.push_back(node);
166 Nodes.erase(node);
167 --NumNodes;
168 node->~ExplodedNode();
169}
170
172 if (ChangedNodes.empty())
173 return;
174
175 // Only periodically reclaim nodes so that we can build up a set of
176 // nodes that meet the reclamation criteria. Freshly created nodes
177 // by definition have no successor, and thus cannot be reclaimed (see below).
178 assert(ReclaimCounter > 0);
179 if (--ReclaimCounter != 0)
180 return;
182
183 for (const auto node : ChangedNodes)
184 if (shouldCollect(node))
185 collectNode(node);
186 ChangedNodes.clear();
187}
188
189//===----------------------------------------------------------------------===//
190// ExplodedNode.
191//===----------------------------------------------------------------------===//
192
193// An NodeGroup's storage type is actually very much like a TinyPtrVector:
194// it can be either a pointer to a single ExplodedNode, or a pointer to a
195// BumpVector allocated with the ExplodedGraph's allocator. This allows the
196// common case of single-node NodeGroups to be implemented with no extra memory.
197//
198// Consequently, each of the NodeGroup methods have up to four cases to handle:
199// 1. The flag is set and this group does not actually contain any nodes.
200// 2. The group is empty, in which case the storage value is null.
201// 3. The group contains a single node.
202// 4. The group contains more than one node.
204using GroupStorage = llvm::PointerUnion<ExplodedNode *, ExplodedNodeVector *>;
205
207 assert(!V->isSink());
208 Preds.addNode(V, G);
209 V->Succs.addNode(this, G);
210}
211
212void ExplodedNode::NodeGroup::replaceNode(ExplodedNode *node) {
213 assert(!getFlag());
214
215 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
216 assert(isa<ExplodedNode *>(Storage));
217 Storage = node;
218 assert(isa<ExplodedNode *>(Storage));
219}
220
221void ExplodedNode::NodeGroup::addNode(ExplodedNode *N, ExplodedGraph &G) {
222 assert(!getFlag());
223
224 GroupStorage &Storage = reinterpret_cast<GroupStorage&>(P);
225 if (Storage.isNull()) {
226 Storage = N;
227 assert(isa<ExplodedNode *>(Storage));
228 return;
229 }
230
231 ExplodedNodeVector *V = dyn_cast<ExplodedNodeVector *>(Storage);
232
233 if (!V) {
234 // Switch from single-node to multi-node representation.
235 auto *Old = cast<ExplodedNode *>(Storage);
236
238 V = new (G.getAllocator()) ExplodedNodeVector(Ctx, 4);
239 V->push_back(Old, Ctx);
240
241 Storage = V;
242 assert(!getFlag());
243 assert(isa<ExplodedNodeVector *>(Storage));
244 }
245
246 V->push_back(N, G.getNodeAllocator());
247}
248
249unsigned ExplodedNode::NodeGroup::size() const {
250 if (getFlag())
251 return 0;
252
253 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
254 if (Storage.isNull())
255 return 0;
256 if (ExplodedNodeVector *V = dyn_cast<ExplodedNodeVector *>(Storage))
257 return V->size();
258 return 1;
259}
260
261ExplodedNode * const *ExplodedNode::NodeGroup::begin() const {
262 if (getFlag())
263 return nullptr;
264
265 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
266 if (Storage.isNull())
267 return nullptr;
268 if (ExplodedNodeVector *V = dyn_cast<ExplodedNodeVector *>(Storage))
269 return V->begin();
270 return Storage.getAddrOfPtr1();
271}
272
273ExplodedNode * const *ExplodedNode::NodeGroup::end() const {
274 if (getFlag())
275 return nullptr;
276
277 const GroupStorage &Storage = reinterpret_cast<const GroupStorage &>(P);
278 if (Storage.isNull())
279 return nullptr;
280 if (ExplodedNodeVector *V = dyn_cast<ExplodedNodeVector *>(Storage))
281 return V->end();
282 return Storage.getAddrOfPtr1() + 1;
283}
284
286 return pred_size() == 1 && succ_size() == 1 &&
287 getFirstPred()->getState()->getID() == getState()->getID() &&
288 getFirstPred()->succ_size() == 1;
289}
290
293 if (auto BEP = P.getAs<BlockEntrance>())
294 return BEP->getBlock();
295
296 // Find the node's current statement in the CFG.
297 // FIXME: getStmtForDiagnostics() does nasty things in order to provide
298 // a valid statement for body farms, do we need this behavior here?
299 if (const Stmt *S = getStmtForDiagnostics())
301 S);
302
303 return nullptr;
304}
305
306static const StackFrame *
309 const StackFrame *ParentSF = SF->getParent();
310 assert(ParentSF && "We don't start analysis from autosynthesized code");
311 while (ParentSF->getAnalysisDeclContext()->isBodyAutosynthesized()) {
312 SF = ParentSF;
313 ParentSF = SF->getParent();
314 assert(ParentSF && "We don't start analysis from autosynthesized code");
315 }
316 return SF;
317}
318
320 // We cannot place diagnostics on autosynthesized code.
321 // Put them onto the call site through which we jumped into autosynthesized
322 // code for the first time.
323 const StackFrame *SF = getStackFrame();
325 // It must be a stack frame because we only autosynthesize functions.
327 }
328 // Otherwise, see if the node's program point directly points to a statement.
329 // FIXME: Refactor into a ProgramPoint method?
331 if (auto SP = P.getAs<StmtPoint>())
332 return SP->getStmt();
333 if (auto BE = P.getAs<BlockEdge>())
334 return BE->getSrc()->getTerminatorStmt();
335 if (auto CE = P.getAs<CallEnter>())
336 return CE->getCallExpr();
337 if (auto CEE = P.getAs<CallExitEnd>())
338 return CEE->getCalleeStackFrame()->getCallSite();
339 if (auto PIPP = P.getAs<PostInitializer>())
340 return PIPP->getInitializer()->getInit();
341 if (auto CEB = P.getAs<CallExitBegin>())
342 return CEB->getReturnStmt();
343 if (auto FEP = P.getAs<FunctionExitPoint>())
344 return FEP->getStmt();
345 if (auto LE = P.getAs<LifetimeEnd>())
346 return LE->getTriggerStmt();
347
348 return nullptr;
349}
350
352 for (const ExplodedNode *N = getFirstSucc(); N; N = N->getFirstSucc()) {
353 if (N->getLocation().isPurgeKind())
354 continue;
355 if (const Stmt *S = N->getStmtForDiagnostics()) {
356 // Check if the statement is '?' or '&&'/'||'. These are "merges",
357 // not actual statement points.
358 switch (S->getStmtClass()) {
359 case Stmt::ChooseExprClass:
360 case Stmt::BinaryConditionalOperatorClass:
361 case Stmt::ConditionalOperatorClass:
362 continue;
363 case Stmt::BinaryOperatorClass: {
364 BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
365 if (Op == BO_LAnd || Op == BO_LOr)
366 continue;
367 break;
368 }
369 default:
370 break;
371 }
372 // We found the statement, so return it.
373 return S;
374 }
375 }
376
377 return nullptr;
378}
379
381 for (const ExplodedNode *N = getFirstPred(); N; N = N->getFirstPred())
382 if (const Stmt *S = N->getStmtForDiagnostics(); S && !isa<CompoundStmt>(S))
383 return S;
384
385 return nullptr;
386}
387
389 if (const Stmt *S = getStmtForDiagnostics())
390 return S;
391
393}
394
396 const ProgramState *State, bool IsSink,
397 bool *IsNew) {
398 // Profile 'State' to determine if we already have an existing node.
399 llvm::FoldingSetNodeID profile;
400 llvm::FoldingSetInsertToken InsertToken;
401
402 NodeTy::Profile(profile, L, State, IsSink);
403 NodeTy *V = Nodes.lookup(profile, InsertToken);
404
405 if (!V) {
406 if (!FreeNodes.empty()) {
407 V = FreeNodes.back();
408 FreeNodes.pop_back();
409 }
410 else {
411 // Allocate a new node.
412 V = getAllocator().Allocate<NodeTy>();
413 }
414
415 ++NumNodes;
416 new (V) NodeTy(L, State, NumNodes, IsSink);
417
419 ChangedNodes.push_back(V);
420
421 // Insert the node into the node set and return it.
422 Nodes.insert(V, InsertToken);
423
424 if (IsNew) *IsNew = true;
425 }
426 else
427 if (IsNew) *IsNew = false;
428
429 return V;
430}
431
433 ProgramStateRef State,
434 int64_t Id,
435 bool IsSink) {
436 NodeTy *V = getAllocator().Allocate<NodeTy>();
437 new (V) NodeTy(L, State, Id, IsSink);
438 return V;
439}
440
441std::unique_ptr<ExplodedGraph>
443 InterExplodedGraphMap *ForwardMap,
444 InterExplodedGraphMap *InverseMap) const {
445 // FIXME: The two-pass algorithm of this function (which was introduced in
446 // 2008) is terribly overcomplicated and should be replaced by a single
447 // (backward) pass.
448
449 if (Nodes.empty())
450 return nullptr;
451
452 using Pass1Ty = llvm::DenseSet<const ExplodedNode *>;
453 Pass1Ty Pass1;
454
455 using Pass2Ty = InterExplodedGraphMap;
456 InterExplodedGraphMap Pass2Scratch;
457 Pass2Ty &Pass2 = ForwardMap ? *ForwardMap : Pass2Scratch;
458
460
461 // ===- Pass 1 (reverse DFS) -===
462 for (const auto Sink : Sinks)
463 if (Sink)
464 WL1.push_back(Sink);
465
466 // Process the first worklist until it is empty.
467 while (!WL1.empty()) {
468 const ExplodedNode *N = WL1.pop_back_val();
469
470 // Have we already visited this node? If so, continue to the next one.
471 if (!Pass1.insert(N).second)
472 continue;
473
474 // If this is the root enqueue it to the second worklist.
475 if (N->Preds.empty()) {
476 assert(N == getRoot() && "Found non-root node with no predecessors!");
477 WL2.push_back(N);
478 continue;
479 }
480
481 // Visit our predecessors and enqueue them.
482 llvm::append_range(WL1, N->Preds);
483 }
484
485 // We didn't hit the root? Return with a null pointer for the new graph.
486 if (WL2.empty())
487 return nullptr;
488
489 assert(WL2.size() == 1 && "There must be only one root!");
490
491 // Create an empty graph.
492 std::unique_ptr<ExplodedGraph> G = std::make_unique<ExplodedGraph>();
493
494 // ===- Pass 2 (forward DFS to construct the new graph) -===
495 while (!WL2.empty()) {
496 const ExplodedNode *N = WL2.pop_back_val();
497
498 auto [Place, Inserted] = Pass2.try_emplace(N);
499
500 // Skip this node if we have already processed it.
501 if (!Inserted)
502 continue;
503
504 // Create the corresponding node in the new graph and record the mapping
505 // from the old node to the new node.
506 ExplodedNode *NewN = G->createUncachedNode(N->getLocation(), N->State,
507 N->getID(), N->isSink());
508 Place->second = NewN;
509
510 // Also record the reverse mapping from the new node to the old node.
511 if (InverseMap) (*InverseMap)[NewN] = N;
512
513 // If this node is the root, designate it as such in the graph.
514 if (N->Preds.empty()) {
515 assert(N == getRoot());
516 G->designateAsRoot(NewN);
517 }
518
519 // In the case that some of the intended predecessors of NewN have already
520 // been created, we should hook them up as predecessors.
521
522 // Walk through the predecessors of 'N' and hook up their corresponding
523 // nodes in the new graph (if any) to the freshly created node.
524 for (const ExplodedNode *Pred : N->Preds) {
525 Pass2Ty::iterator PI = Pass2.find(Pred);
526 if (PI == Pass2.end())
527 continue;
528
529 NewN->addPredecessor(const_cast<ExplodedNode *>(PI->second), *G);
530 }
531
532 // In the case that some of the intended successors of NewN have already
533 // been created, we should hook them up as successors. Otherwise, enqueue
534 // the new nodes from the original graph that should have nodes created
535 // in the new graph.
536 for (const ExplodedNode *Succ : N->Succs) {
537 Pass2Ty::iterator PI = Pass2.find(Succ);
538 if (PI != Pass2.end()) {
539 const_cast<ExplodedNode *>(PI->second)->addPredecessor(NewN, *G);
540 continue;
541 }
542
543 // Enqueue nodes to the worklist that were marked during pass 1.
544 if (Pass1.count(Succ))
545 WL2.push_back(Succ);
546 }
547 }
548
549 return G;
550}
551
552llvm::GraphTraits<ExplodedGraph *>::nodes_iterator
553llvm::GraphTraits<ExplodedGraph *>::nodes_begin(const GraphTy G) {
554 return df_begin(G);
555}
556
557llvm::GraphTraits<ExplodedGraph *>::nodes_iterator
558llvm::GraphTraits<ExplodedGraph *>::nodes_end(const GraphTy G) {
559 return df_end(G);
560}
#define V(N, I)
static const StackFrame * findTopAutosynthesizedParentStackFrame(const StackFrame *SF)
llvm::PointerUnion< ExplodedNode *, ExplodedNodeVector * > GroupStorage
BumpVector< ExplodedNode * > ExplodedNodeVector
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Represents a single basic block in a source-level CFG.
Definition CFG.h:651
const CFGBlock * getBlock(const Stmt *S) const
Returns the CFGBlock the specified Stmt* appears in.
Represents a point when we begin processing an inlined call.
Represents a point when we start the call exit sequence (for inlined call).
Represents a point when we finish the call exit sequence (for inlined call).
This represents one expression.
Definition Expr.h:114
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
Represents a point when the lifetime of an automatic object ends.
bool isConsumedExpr(Expr *E) const
Represents a program point after a store evaluation.
Represents a program point just before an implicit call event.
Represents a point after we ran remove dead bindings BEFORE processing the given statement.
const ProgramPointTag * getTag() const
bool isPurgeKind()
Is this a program point corresponding to purge/removal of dead symbols and bindings.
T castAs() const
Convert to the specified ProgramPoint type, asserting that this ProgramPoint is of the desired type.
const StackFrame * getStackFrame() const
std::optional< T > getAs() const
Convert to the specified ProgramPoint type, returning std::nullopt if this ProgramPoint is not of the...
It represents a stack frame of the call stack.
const ParentMap & getParentMap() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const Expr * getCallSite() const
const StackFrame * getParent() const
It might return null.
const Stmt * getStmt() const
Stmt - This represents one statement.
Definition Stmt.h:85
static bool isCallStmt(const Stmt *S)
Returns true if this is a statement is a function or method call of some kind.
std::unique_ptr< ExplodedGraph > trim(ArrayRef< const NodeTy * > Nodes, InterExplodedGraphMap *ForwardMap=nullptr, InterExplodedGraphMap *InverseMap=nullptr) const
Creates a trimmed version of the graph that only contains paths leading to the given nodes.
ExplodedNode * getNode(const ProgramPoint &L, const ProgramState *State, bool IsSink=false, bool *IsNew=nullptr)
Retrieve the node associated with a (Location, State) pair, where the 'Location' is a ProgramPoint in...
BumpVectorContext & getNodeAllocator()
unsigned ReclaimCounter
Counter to determine when to reclaim nodes.
NodeVector ChangedNodes
A list of recently allocated nodes that can potentially be recycled.
int64_t NumNodes
NumNodes - The number of nodes in the graph.
ExplodedNode * addEndOfPath(ExplodedNode *V)
addEndOfPath - Add an untyped node to the set of EOP nodes.
unsigned ReclaimNodeInterval
Determines how often nodes are reclaimed.
NodeVector EndNodes
The nodes in the simulation graph which have been specially marked as the endpoint of an abstract sim...
void reclaimRecentlyAllocatedNodes()
Reclaim "uninteresting" nodes created since the last time this method was called.
static bool isInterestingLValueExpr(const Expr *Ex)
Returns true if nodes for the given expression kind are always kept around.
llvm::BumpPtrAllocator & getAllocator()
ExplodedNode * getRoot() const
Get the root node of the graph.
ExplodedNode * createUncachedNode(const ProgramPoint &L, ProgramStateRef State, int64_t Id, bool IsSink=false)
Create a node for a (Location, State) pair, but don't store it for deduplication later.
llvm::FoldingSet< ExplodedNode > Nodes
Nodes - The nodes in the graph.
NodeVector FreeNodes
A list of nodes that can be reused.
const CFGBlock * getCFGBlock() const
const ProgramStateRef & getState() const
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
bool isTrivial() const
The node is trivial if it has only one successor, only one predecessor, it's predecessor has only one...
const Stmt * getPreviousStmtForDiagnostics() const
Find the statement that was executed immediately before this node.
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
void addPredecessor(ExplodedNode *V, ExplodedGraph &G)
addPredeccessor - Adds a predecessor to the current node, and in tandem add this node as a successor ...
ExplodedNode * getFirstSucc()
unsigned pred_size() const
ExplodedNode(const ProgramPoint &loc, ProgramStateRef state, int64_t Id, bool IsSink)
static void Profile(llvm::FoldingSetNodeID &ID, const ProgramPoint &Loc, const ProgramState *state, bool IsSink)
const Stmt * getNextStmtForDiagnostics() const
Find the next statement that was executed on this node's execution path.
const Stmt * getCurrentOrPreviousStmtForDiagnostics() const
Find the statement that was executed at or immediately before this node.
ExplodedNode * getFirstPred()
unsigned succ_size() const
const StackFrame * getStackFrame() const
ProgramState - This class encapsulates:
llvm::DenseMap< const ExplodedNode *, const ExplodedNode * > InterExplodedGraphMap
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
U cast(CodeGen::Address addr)
Definition Address.h:327