1 //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a meta-engine for path-sensitive dataflow analysis that
11 // is built on GREngine, but provides the boilerplate to execute transfer
12 // functions and build the ExplodedGraph at the expression level.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17 #include "PrettyStackTraceLocationContext.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ParentMap.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/Stmt.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/AST/Type.h"
32 #include "clang/Analysis/AnalysisDeclContext.h"
33 #include "clang/Analysis/CFG.h"
34 #include "clang/Analysis/ConstructionContext.h"
35 #include "clang/Analysis/ProgramPoint.h"
36 #include "clang/Basic/IdentifierTable.h"
37 #include "clang/Basic/LLVM.h"
38 #include "clang/Basic/LangOptions.h"
39 #include "clang/Basic/PrettyStackTrace.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/Specifiers.h"
43 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
44 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
45 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
46 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
48 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
49 #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
50 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
51 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
52 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
53 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
54 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
55 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
56 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
57 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
58 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
59 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
60 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
61 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
62 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
63 #include "llvm/ADT/APSInt.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/ImmutableMap.h"
66 #include "llvm/ADT/ImmutableSet.h"
67 #include "llvm/ADT/Optional.h"
68 #include "llvm/ADT/SmallVector.h"
69 #include "llvm/ADT/Statistic.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/DOTGraphTraits.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/GraphWriter.h"
75 #include "llvm/Support/SaveAndRestore.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include <cassert>
78 #include <cstdint>
79 #include <memory>
80 #include <string>
81 #include <tuple>
82 #include <utility>
83 #include <vector>
84
85 using namespace clang;
86 using namespace ento;
87
88 #define DEBUG_TYPE "ExprEngine"
89
90 STATISTIC(NumRemoveDeadBindings,
91 "The # of times RemoveDeadBindings is called");
92 STATISTIC(NumMaxBlockCountReached,
93 "The # of aborted paths due to reaching the maximum block count in "
94 "a top level function");
95 STATISTIC(NumMaxBlockCountReachedInInlined,
96 "The # of aborted paths due to reaching the maximum block count in "
97 "an inlined function");
98 STATISTIC(NumTimesRetriedWithoutInlining,
99 "The # of times we re-evaluated a call without inlining");
100
101
102 //===----------------------------------------------------------------------===//
103 // Internal program state traits.
104 //===----------------------------------------------------------------------===//
105
106 // When modeling a C++ constructor, for a variety of reasons we need to track
107 // the location of the object for the duration of its ConstructionContext.
108 // ObjectsUnderConstruction maps statements within the construction context
109 // to the object's location, so that on every such statement the location
110 // could have been retrieved.
111
112 /// ConstructedObjectKey is used for being able to find the path-sensitive
113 /// memory region of a freshly constructed object while modeling the AST node
114 /// that syntactically represents the object that is being constructed.
115 /// Semantics of such nodes may sometimes require access to the region that's
116 /// not otherwise present in the program state, or to the very fact that
117 /// the construction context was present and contained references to these
118 /// AST nodes.
119 class ConstructedObjectKey {
120 typedef std::pair<ConstructionContextItem, const LocationContext *>
121 ConstructedObjectKeyImpl;
122
123 const ConstructedObjectKeyImpl Impl;
124
getAnyASTNodePtr() const125 const void *getAnyASTNodePtr() const {
126 if (const Stmt *S = getItem().getStmtOrNull())
127 return S;
128 else
129 return getItem().getCXXCtorInitializer();
130 }
131
132 public:
ConstructedObjectKey(const ConstructionContextItem & Item,const LocationContext * LC)133 explicit ConstructedObjectKey(const ConstructionContextItem &Item,
134 const LocationContext *LC)
135 : Impl(Item, LC) {}
136
getItem() const137 const ConstructionContextItem &getItem() const { return Impl.first; }
getLocationContext() const138 const LocationContext *getLocationContext() const { return Impl.second; }
139
print(llvm::raw_ostream & OS,PrinterHelper * Helper,PrintingPolicy & PP)140 void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) {
141 OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ','
142 << getItem().getKindAsString();
143 if (getItem().getKind() == ConstructionContextItem::ArgumentKind)
144 OS << " #" << getItem().getIndex();
145 OS << ") ";
146 if (const Stmt *S = getItem().getStmtOrNull()) {
147 S->printPretty(OS, Helper, PP);
148 } else {
149 const CXXCtorInitializer *I = getItem().getCXXCtorInitializer();
150 OS << I->getAnyMember()->getNameAsString();
151 }
152 }
153
Profile(llvm::FoldingSetNodeID & ID) const154 void Profile(llvm::FoldingSetNodeID &ID) const {
155 ID.Add(Impl.first);
156 ID.AddPointer(Impl.second);
157 }
158
operator ==(const ConstructedObjectKey & RHS) const159 bool operator==(const ConstructedObjectKey &RHS) const {
160 return Impl == RHS.Impl;
161 }
162
operator <(const ConstructedObjectKey & RHS) const163 bool operator<(const ConstructedObjectKey &RHS) const {
164 return Impl < RHS.Impl;
165 }
166 };
167
168 typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
169 ObjectsUnderConstructionMap;
170 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
171 ObjectsUnderConstructionMap)
172
173 //===----------------------------------------------------------------------===//
174 // Engine construction and deletion.
175 //===----------------------------------------------------------------------===//
176
177 static const char* TagProviderName = "ExprEngine";
178
ExprEngine(cross_tu::CrossTranslationUnitContext & CTU,AnalysisManager & mgr,bool gcEnabled,SetOfConstDecls * VisitedCalleesIn,FunctionSummariesTy * FS,InliningModes HowToInlineIn)179 ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU,
180 AnalysisManager &mgr, bool gcEnabled,
181 SetOfConstDecls *VisitedCalleesIn,
182 FunctionSummariesTy *FS,
183 InliningModes HowToInlineIn)
184 : CTU(CTU), AMgr(mgr),
185 AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
186 Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
187 StateMgr(getContext(), mgr.getStoreManagerCreator(),
188 mgr.getConstraintManagerCreator(), G.getAllocator(),
189 this),
190 SymMgr(StateMgr.getSymbolManager()),
191 svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
192 ObjCGCEnabled(gcEnabled), BR(mgr, *this),
193 VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
194 unsigned TrimInterval = mgr.options.getGraphTrimInterval();
195 if (TrimInterval != 0) {
196 // Enable eager node reclaimation when constructing the ExplodedGraph.
197 G.enableNodeReclamation(TrimInterval);
198 }
199 }
200
~ExprEngine()201 ExprEngine::~ExprEngine() {
202 BR.FlushReports();
203 }
204
205 //===----------------------------------------------------------------------===//
206 // Utility methods.
207 //===----------------------------------------------------------------------===//
208
getInitialState(const LocationContext * InitLoc)209 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
210 ProgramStateRef state = StateMgr.getInitialState(InitLoc);
211 const Decl *D = InitLoc->getDecl();
212
213 // Preconditions.
214 // FIXME: It would be nice if we had a more general mechanism to add
215 // such preconditions. Some day.
216 do {
217 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
218 // Precondition: the first argument of 'main' is an integer guaranteed
219 // to be > 0.
220 const IdentifierInfo *II = FD->getIdentifier();
221 if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
222 break;
223
224 const ParmVarDecl *PD = FD->getParamDecl(0);
225 QualType T = PD->getType();
226 const auto *BT = dyn_cast<BuiltinType>(T);
227 if (!BT || !BT->isInteger())
228 break;
229
230 const MemRegion *R = state->getRegion(PD, InitLoc);
231 if (!R)
232 break;
233
234 SVal V = state->getSVal(loc::MemRegionVal(R));
235 SVal Constraint_untested = evalBinOp(state, BO_GT, V,
236 svalBuilder.makeZeroVal(T),
237 svalBuilder.getConditionType());
238
239 Optional<DefinedOrUnknownSVal> Constraint =
240 Constraint_untested.getAs<DefinedOrUnknownSVal>();
241
242 if (!Constraint)
243 break;
244
245 if (ProgramStateRef newState = state->assume(*Constraint, true))
246 state = newState;
247 }
248 break;
249 }
250 while (false);
251
252 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
253 // Precondition: 'self' is always non-null upon entry to an Objective-C
254 // method.
255 const ImplicitParamDecl *SelfD = MD->getSelfDecl();
256 const MemRegion *R = state->getRegion(SelfD, InitLoc);
257 SVal V = state->getSVal(loc::MemRegionVal(R));
258
259 if (Optional<Loc> LV = V.getAs<Loc>()) {
260 // Assume that the pointer value in 'self' is non-null.
261 state = state->assume(*LV, true);
262 assert(state && "'self' cannot be null");
263 }
264 }
265
266 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
267 if (!MD->isStatic()) {
268 // Precondition: 'this' is always non-null upon entry to the
269 // top-level function. This is our starting assumption for
270 // analyzing an "open" program.
271 const StackFrameContext *SFC = InitLoc->getStackFrame();
272 if (SFC->getParent() == nullptr) {
273 loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
274 SVal V = state->getSVal(L);
275 if (Optional<Loc> LV = V.getAs<Loc>()) {
276 state = state->assume(*LV, true);
277 assert(state && "'this' cannot be null");
278 }
279 }
280 }
281 }
282
283 return state;
284 }
285
286 ProgramStateRef
createTemporaryRegionIfNeeded(ProgramStateRef State,const LocationContext * LC,const Expr * InitWithAdjustments,const Expr * Result)287 ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
288 const LocationContext *LC,
289 const Expr *InitWithAdjustments,
290 const Expr *Result) {
291 // FIXME: This function is a hack that works around the quirky AST
292 // we're often having with respect to C++ temporaries. If only we modelled
293 // the actual execution order of statements properly in the CFG,
294 // all the hassle with adjustments would not be necessary,
295 // and perhaps the whole function would be removed.
296 SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
297 if (!Result) {
298 // If we don't have an explicit result expression, we're in "if needed"
299 // mode. Only create a region if the current value is a NonLoc.
300 if (!InitValWithAdjustments.getAs<NonLoc>())
301 return State;
302 Result = InitWithAdjustments;
303 } else {
304 // We need to create a region no matter what. For sanity, make sure we don't
305 // try to stuff a Loc into a non-pointer temporary region.
306 assert(!InitValWithAdjustments.getAs<Loc>() ||
307 Loc::isLocType(Result->getType()) ||
308 Result->getType()->isMemberPointerType());
309 }
310
311 ProgramStateManager &StateMgr = State->getStateManager();
312 MemRegionManager &MRMgr = StateMgr.getRegionManager();
313 StoreManager &StoreMgr = StateMgr.getStoreManager();
314
315 // MaterializeTemporaryExpr may appear out of place, after a few field and
316 // base-class accesses have been made to the object, even though semantically
317 // it is the whole object that gets materialized and lifetime-extended.
318 //
319 // For example:
320 //
321 // `-MaterializeTemporaryExpr
322 // `-MemberExpr
323 // `-CXXTemporaryObjectExpr
324 //
325 // instead of the more natural
326 //
327 // `-MemberExpr
328 // `-MaterializeTemporaryExpr
329 // `-CXXTemporaryObjectExpr
330 //
331 // Use the usual methods for obtaining the expression of the base object,
332 // and record the adjustments that we need to make to obtain the sub-object
333 // that the whole expression 'Ex' refers to. This trick is usual,
334 // in the sense that CodeGen takes a similar route.
335
336 SmallVector<const Expr *, 2> CommaLHSs;
337 SmallVector<SubobjectAdjustment, 2> Adjustments;
338
339 const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
340 CommaLHSs, Adjustments);
341
342 // Take the region for Init, i.e. for the whole object. If we do not remember
343 // the region in which the object originally was constructed, come up with
344 // a new temporary region out of thin air and copy the contents of the object
345 // (which are currently present in the Environment, because Init is an rvalue)
346 // into that region. This is not correct, but it is better than nothing.
347 const TypedValueRegion *TR = nullptr;
348 if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
349 if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
350 State = finishObjectConstruction(State, MT, LC);
351 State = State->BindExpr(Result, LC, *V);
352 return State;
353 } else {
354 StorageDuration SD = MT->getStorageDuration();
355 // If this object is bound to a reference with static storage duration, we
356 // put it in a different region to prevent "address leakage" warnings.
357 if (SD == SD_Static || SD == SD_Thread) {
358 TR = MRMgr.getCXXStaticTempObjectRegion(Init);
359 } else {
360 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
361 }
362 }
363 } else {
364 TR = MRMgr.getCXXTempObjectRegion(Init, LC);
365 }
366
367 SVal Reg = loc::MemRegionVal(TR);
368 SVal BaseReg = Reg;
369
370 // Make the necessary adjustments to obtain the sub-object.
371 for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
372 const SubobjectAdjustment &Adj = *I;
373 switch (Adj.Kind) {
374 case SubobjectAdjustment::DerivedToBaseAdjustment:
375 Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
376 break;
377 case SubobjectAdjustment::FieldAdjustment:
378 Reg = StoreMgr.getLValueField(Adj.Field, Reg);
379 break;
380 case SubobjectAdjustment::MemberPointerAdjustment:
381 // FIXME: Unimplemented.
382 State = State->invalidateRegions(Reg, InitWithAdjustments,
383 currBldrCtx->blockCount(), LC, true,
384 nullptr, nullptr, nullptr);
385 return State;
386 }
387 }
388
389 // What remains is to copy the value of the object to the new region.
390 // FIXME: In other words, what we should always do is copy value of the
391 // Init expression (which corresponds to the bigger object) to the whole
392 // temporary region TR. However, this value is often no longer present
393 // in the Environment. If it has disappeared, we instead invalidate TR.
394 // Still, what we can do is assign the value of expression Ex (which
395 // corresponds to the sub-object) to the TR's sub-region Reg. At least,
396 // values inside Reg would be correct.
397 SVal InitVal = State->getSVal(Init, LC);
398 if (InitVal.isUnknown()) {
399 InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
400 currBldrCtx->blockCount());
401 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
402
403 // Then we'd need to take the value that certainly exists and bind it
404 // over.
405 if (InitValWithAdjustments.isUnknown()) {
406 // Try to recover some path sensitivity in case we couldn't
407 // compute the value.
408 InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
409 Result, LC, InitWithAdjustments->getType(),
410 currBldrCtx->blockCount());
411 }
412 State =
413 State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
414 } else {
415 State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
416 }
417
418 // The result expression would now point to the correct sub-region of the
419 // newly created temporary region. Do this last in order to getSVal of Init
420 // correctly in case (Result == Init).
421 State = State->BindExpr(Result, LC, Reg);
422
423 // Notify checkers once for two bindLoc()s.
424 State = processRegionChange(State, TR, LC);
425
426 return State;
427 }
428
429 ProgramStateRef
addObjectUnderConstruction(ProgramStateRef State,const ConstructionContextItem & Item,const LocationContext * LC,SVal V)430 ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
431 const ConstructionContextItem &Item,
432 const LocationContext *LC, SVal V) {
433 ConstructedObjectKey Key(Item, LC->getStackFrame());
434 // FIXME: Currently the state might already contain the marker due to
435 // incorrect handling of temporaries bound to default parameters.
436 assert(!State->get<ObjectsUnderConstruction>(Key) ||
437 Key.getItem().getKind() ==
438 ConstructionContextItem::TemporaryDestructorKind);
439 return State->set<ObjectsUnderConstruction>(Key, V);
440 }
441
442 Optional<SVal>
getObjectUnderConstruction(ProgramStateRef State,const ConstructionContextItem & Item,const LocationContext * LC)443 ExprEngine::getObjectUnderConstruction(ProgramStateRef State,
444 const ConstructionContextItem &Item,
445 const LocationContext *LC) {
446 ConstructedObjectKey Key(Item, LC->getStackFrame());
447 return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
448 }
449
450 ProgramStateRef
finishObjectConstruction(ProgramStateRef State,const ConstructionContextItem & Item,const LocationContext * LC)451 ExprEngine::finishObjectConstruction(ProgramStateRef State,
452 const ConstructionContextItem &Item,
453 const LocationContext *LC) {
454 ConstructedObjectKey Key(Item, LC->getStackFrame());
455 assert(State->contains<ObjectsUnderConstruction>(Key));
456 return State->remove<ObjectsUnderConstruction>(Key);
457 }
458
elideDestructor(ProgramStateRef State,const CXXBindTemporaryExpr * BTE,const LocationContext * LC)459 ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
460 const CXXBindTemporaryExpr *BTE,
461 const LocationContext *LC) {
462 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
463 // FIXME: Currently the state might already contain the marker due to
464 // incorrect handling of temporaries bound to default parameters.
465 return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
466 }
467
468 ProgramStateRef
cleanupElidedDestructor(ProgramStateRef State,const CXXBindTemporaryExpr * BTE,const LocationContext * LC)469 ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
470 const CXXBindTemporaryExpr *BTE,
471 const LocationContext *LC) {
472 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
473 assert(State->contains<ObjectsUnderConstruction>(Key));
474 return State->remove<ObjectsUnderConstruction>(Key);
475 }
476
isDestructorElided(ProgramStateRef State,const CXXBindTemporaryExpr * BTE,const LocationContext * LC)477 bool ExprEngine::isDestructorElided(ProgramStateRef State,
478 const CXXBindTemporaryExpr *BTE,
479 const LocationContext *LC) {
480 ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
481 return State->contains<ObjectsUnderConstruction>(Key);
482 }
483
areAllObjectsFullyConstructed(ProgramStateRef State,const LocationContext * FromLC,const LocationContext * ToLC)484 bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
485 const LocationContext *FromLC,
486 const LocationContext *ToLC) {
487 const LocationContext *LC = FromLC;
488 while (LC != ToLC) {
489 assert(LC && "ToLC must be a parent of FromLC!");
490 for (auto I : State->get<ObjectsUnderConstruction>())
491 if (I.first.getLocationContext() == LC)
492 return false;
493
494 LC = LC->getParent();
495 }
496 return true;
497 }
498
499
500 //===----------------------------------------------------------------------===//
501 // Top-level transfer function logic (Dispatcher).
502 //===----------------------------------------------------------------------===//
503
504 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
505 /// logic for handling assumptions on symbolic values.
processAssume(ProgramStateRef state,SVal cond,bool assumption)506 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
507 SVal cond, bool assumption) {
508 return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
509 }
510
511 ProgramStateRef
processRegionChanges(ProgramStateRef state,const InvalidatedSymbols * invalidated,ArrayRef<const MemRegion * > Explicits,ArrayRef<const MemRegion * > Regions,const LocationContext * LCtx,const CallEvent * Call)512 ExprEngine::processRegionChanges(ProgramStateRef state,
513 const InvalidatedSymbols *invalidated,
514 ArrayRef<const MemRegion *> Explicits,
515 ArrayRef<const MemRegion *> Regions,
516 const LocationContext *LCtx,
517 const CallEvent *Call) {
518 return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
519 Explicits, Regions,
520 LCtx, Call);
521 }
522
printObjectsUnderConstructionForContext(raw_ostream & Out,ProgramStateRef State,const char * NL,const char * Sep,const LocationContext * LC)523 static void printObjectsUnderConstructionForContext(raw_ostream &Out,
524 ProgramStateRef State,
525 const char *NL,
526 const char *Sep,
527 const LocationContext *LC) {
528 PrintingPolicy PP =
529 LC->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
530 for (auto I : State->get<ObjectsUnderConstruction>()) {
531 ConstructedObjectKey Key = I.first;
532 SVal Value = I.second;
533 if (Key.getLocationContext() != LC)
534 continue;
535 Key.print(Out, nullptr, PP);
536 Out << " : " << Value << NL;
537 }
538 }
539
printState(raw_ostream & Out,ProgramStateRef State,const char * NL,const char * Sep,const LocationContext * LCtx)540 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
541 const char *NL, const char *Sep,
542 const LocationContext *LCtx) {
543 if (LCtx) {
544 if (!State->get<ObjectsUnderConstruction>().isEmpty()) {
545 Out << Sep << "Objects under construction:" << NL;
546
547 LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) {
548 printObjectsUnderConstructionForContext(Out, State, NL, Sep, LC);
549 });
550 }
551 }
552
553 getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
554 }
555
processEndWorklist(bool hasWorkRemaining)556 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
557 getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
558 }
559
processCFGElement(const CFGElement E,ExplodedNode * Pred,unsigned StmtIdx,NodeBuilderContext * Ctx)560 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
561 unsigned StmtIdx, NodeBuilderContext *Ctx) {
562 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
563 currStmtIdx = StmtIdx;
564 currBldrCtx = Ctx;
565
566 switch (E.getKind()) {
567 case CFGElement::Statement:
568 case CFGElement::Constructor:
569 case CFGElement::CXXRecordTypedCall:
570 ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
571 return;
572 case CFGElement::Initializer:
573 ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
574 return;
575 case CFGElement::NewAllocator:
576 ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
577 Pred);
578 return;
579 case CFGElement::AutomaticObjectDtor:
580 case CFGElement::DeleteDtor:
581 case CFGElement::BaseDtor:
582 case CFGElement::MemberDtor:
583 case CFGElement::TemporaryDtor:
584 ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
585 return;
586 case CFGElement::LoopExit:
587 ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
588 return;
589 case CFGElement::LifetimeEnds:
590 case CFGElement::ScopeBegin:
591 case CFGElement::ScopeEnd:
592 return;
593 }
594 }
595
shouldRemoveDeadBindings(AnalysisManager & AMgr,const Stmt * S,const ExplodedNode * Pred,const LocationContext * LC)596 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
597 const Stmt *S,
598 const ExplodedNode *Pred,
599 const LocationContext *LC) {
600 // Are we never purging state values?
601 if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
602 return false;
603
604 // Is this the beginning of a basic block?
605 if (Pred->getLocation().getAs<BlockEntrance>())
606 return true;
607
608 // Is this on a non-expression?
609 if (!isa<Expr>(S))
610 return true;
611
612 // Run before processing a call.
613 if (CallEvent::isCallStmt(S))
614 return true;
615
616 // Is this an expression that is consumed by another expression? If so,
617 // postpone cleaning out the state.
618 ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
619 return !PM.isConsumedExpr(cast<Expr>(S));
620 }
621
removeDead(ExplodedNode * Pred,ExplodedNodeSet & Out,const Stmt * ReferenceStmt,const LocationContext * LC,const Stmt * DiagnosticStmt,ProgramPoint::Kind K)622 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
623 const Stmt *ReferenceStmt,
624 const LocationContext *LC,
625 const Stmt *DiagnosticStmt,
626 ProgramPoint::Kind K) {
627 assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
628 ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
629 && "PostStmt is not generally supported by the SymbolReaper yet");
630 assert(LC && "Must pass the current (or expiring) LocationContext");
631
632 if (!DiagnosticStmt) {
633 DiagnosticStmt = ReferenceStmt;
634 assert(DiagnosticStmt && "Required for clearing a LocationContext");
635 }
636
637 NumRemoveDeadBindings++;
638 ProgramStateRef CleanedState = Pred->getState();
639
640 // LC is the location context being destroyed, but SymbolReaper wants a
641 // location context that is still live. (If this is the top-level stack
642 // frame, this will be null.)
643 if (!ReferenceStmt) {
644 assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
645 "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
646 LC = LC->getParent();
647 }
648
649 const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
650 SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
651
652 for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
653 if (SymbolRef Sym = I.second.getAsSymbol())
654 SymReaper.markLive(Sym);
655 if (const MemRegion *MR = I.second.getAsRegion())
656 SymReaper.markLive(MR);
657 }
658
659 getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
660
661 // Create a state in which dead bindings are removed from the environment
662 // and the store. TODO: The function should just return new env and store,
663 // not a new state.
664 CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
665
666 // Process any special transfer function for dead symbols.
667 // A tag to track convenience transitions, which can be removed at cleanup.
668 static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
669 if (!SymReaper.hasDeadSymbols()) {
670 // Generate a CleanedNode that has the environment and store cleaned
671 // up. Since no symbols are dead, we can optimize and not clean out
672 // the constraint manager.
673 StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
674 Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
675
676 } else {
677 // Call checkers with the non-cleaned state so that they could query the
678 // values of the soon to be dead symbols.
679 ExplodedNodeSet CheckedSet;
680 getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
681 DiagnosticStmt, *this, K);
682
683 // For each node in CheckedSet, generate CleanedNodes that have the
684 // environment, the store, and the constraints cleaned up but have the
685 // user-supplied states as the predecessors.
686 StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
687 for (const auto I : CheckedSet) {
688 ProgramStateRef CheckerState = I->getState();
689
690 // The constraint manager has not been cleaned up yet, so clean up now.
691 CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
692 SymReaper);
693
694 assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
695 "Checkers are not allowed to modify the Environment as a part of "
696 "checkDeadSymbols processing.");
697 assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
698 "Checkers are not allowed to modify the Store as a part of "
699 "checkDeadSymbols processing.");
700
701 // Create a state based on CleanedState with CheckerState GDM and
702 // generate a transition to that state.
703 ProgramStateRef CleanedCheckerSt =
704 StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
705 Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
706 }
707 }
708 }
709
ProcessStmt(const Stmt * currStmt,ExplodedNode * Pred)710 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
711 // Reclaim any unnecessary nodes in the ExplodedGraph.
712 G.reclaimRecentlyAllocatedNodes();
713
714 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
715 currStmt->getLocStart(),
716 "Error evaluating statement");
717
718 // Remove dead bindings and symbols.
719 ExplodedNodeSet CleanedStates;
720 if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
721 Pred->getLocationContext())) {
722 removeDead(Pred, CleanedStates, currStmt,
723 Pred->getLocationContext());
724 } else
725 CleanedStates.Add(Pred);
726
727 // Visit the statement.
728 ExplodedNodeSet Dst;
729 for (const auto I : CleanedStates) {
730 ExplodedNodeSet DstI;
731 // Visit the statement.
732 Visit(currStmt, I, DstI);
733 Dst.insert(DstI);
734 }
735
736 // Enqueue the new nodes onto the work list.
737 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
738 }
739
ProcessLoopExit(const Stmt * S,ExplodedNode * Pred)740 void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
741 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
742 S->getLocStart(),
743 "Error evaluating end of the loop");
744 ExplodedNodeSet Dst;
745 Dst.Add(Pred);
746 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
747 ProgramStateRef NewState = Pred->getState();
748
749 if(AMgr.options.shouldUnrollLoops())
750 NewState = processLoopEnd(S, NewState);
751
752 LoopExit PP(S, Pred->getLocationContext());
753 Bldr.generateNode(PP, NewState, Pred);
754 // Enqueue the new nodes onto the work list.
755 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
756 }
757
ProcessInitializer(const CFGInitializer CFGInit,ExplodedNode * Pred)758 void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit,
759 ExplodedNode *Pred) {
760 const CXXCtorInitializer *BMI = CFGInit.getInitializer();
761 const Expr *Init = BMI->getInit()->IgnoreImplicit();
762 const LocationContext *LC = Pred->getLocationContext();
763
764 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
765 BMI->getSourceLocation(),
766 "Error evaluating initializer");
767
768 // We don't clean up dead bindings here.
769 const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
770 const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
771
772 ProgramStateRef State = Pred->getState();
773 SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
774
775 ExplodedNodeSet Tmp;
776 SVal FieldLoc;
777
778 // Evaluate the initializer, if necessary
779 if (BMI->isAnyMemberInitializer()) {
780 // Constructors build the object directly in the field,
781 // but non-objects must be copied in from the initializer.
782 if (getObjectUnderConstruction(State, BMI, LC)) {
783 // The field was directly constructed, so there is no need to bind.
784 // But we still need to stop tracking the object under construction.
785 State = finishObjectConstruction(State, BMI, LC);
786 NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
787 PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
788 Bldr.generateNode(PS, State, Pred);
789 } else {
790 const ValueDecl *Field;
791 if (BMI->isIndirectMemberInitializer()) {
792 Field = BMI->getIndirectMember();
793 FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
794 } else {
795 Field = BMI->getMember();
796 FieldLoc = State->getLValue(BMI->getMember(), thisVal);
797 }
798
799 SVal InitVal;
800 if (Init->getType()->isArrayType()) {
801 // Handle arrays of trivial type. We can represent this with a
802 // primitive load/copy from the base array region.
803 const ArraySubscriptExpr *ASE;
804 while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
805 Init = ASE->getBase()->IgnoreImplicit();
806
807 SVal LValue = State->getSVal(Init, stackFrame);
808 if (!Field->getType()->isReferenceType())
809 if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
810 InitVal = State->getSVal(*LValueLoc);
811
812 // If we fail to get the value for some reason, use a symbolic value.
813 if (InitVal.isUnknownOrUndef()) {
814 SValBuilder &SVB = getSValBuilder();
815 InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
816 Field->getType(),
817 currBldrCtx->blockCount());
818 }
819 } else {
820 InitVal = State->getSVal(BMI->getInit(), stackFrame);
821 }
822
823 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
824 evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
825 }
826 } else {
827 assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
828 Tmp.insert(Pred);
829 // We already did all the work when visiting the CXXConstructExpr.
830 }
831
832 // Construct PostInitializer nodes whether the state changed or not,
833 // so that the diagnostics don't get confused.
834 PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
835 ExplodedNodeSet Dst;
836 NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
837 for (const auto I : Tmp) {
838 ProgramStateRef State = I->getState();
839 Bldr.generateNode(PP, State, I);
840 }
841
842 // Enqueue the new nodes onto the work list.
843 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
844 }
845
ProcessImplicitDtor(const CFGImplicitDtor D,ExplodedNode * Pred)846 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
847 ExplodedNode *Pred) {
848 ExplodedNodeSet Dst;
849 switch (D.getKind()) {
850 case CFGElement::AutomaticObjectDtor:
851 ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
852 break;
853 case CFGElement::BaseDtor:
854 ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
855 break;
856 case CFGElement::MemberDtor:
857 ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
858 break;
859 case CFGElement::TemporaryDtor:
860 ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
861 break;
862 case CFGElement::DeleteDtor:
863 ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
864 break;
865 default:
866 llvm_unreachable("Unexpected dtor kind.");
867 }
868
869 // Enqueue the new nodes onto the work list.
870 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
871 }
872
ProcessNewAllocator(const CXXNewExpr * NE,ExplodedNode * Pred)873 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
874 ExplodedNode *Pred) {
875 ExplodedNodeSet Dst;
876 AnalysisManager &AMgr = getAnalysisManager();
877 AnalyzerOptions &Opts = AMgr.options;
878 // TODO: We're not evaluating allocators for all cases just yet as
879 // we're not handling the return value correctly, which causes false
880 // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
881 if (Opts.mayInlineCXXAllocator())
882 VisitCXXNewAllocatorCall(NE, Pred, Dst);
883 else {
884 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
885 const LocationContext *LCtx = Pred->getLocationContext();
886 PostImplicitCall PP(NE->getOperatorNew(), NE->getLocStart(), LCtx);
887 Bldr.generateNode(PP, Pred->getState(), Pred);
888 }
889 Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
890 }
891
ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,ExplodedNode * Pred,ExplodedNodeSet & Dst)892 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
893 ExplodedNode *Pred,
894 ExplodedNodeSet &Dst) {
895 const VarDecl *varDecl = Dtor.getVarDecl();
896 QualType varType = varDecl->getType();
897
898 ProgramStateRef state = Pred->getState();
899 SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
900 const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
901
902 if (varType->isReferenceType()) {
903 const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
904 if (!ValueRegion) {
905 // FIXME: This should not happen. The language guarantees a presence
906 // of a valid initializer here, so the reference shall not be undefined.
907 // It seems that we're calling destructors over variables that
908 // were not initialized yet.
909 return;
910 }
911 Region = ValueRegion->getBaseRegion();
912 varType = cast<TypedValueRegion>(Region)->getValueType();
913 }
914
915 // FIXME: We need to run the same destructor on every element of the array.
916 // This workaround will just run the first destructor (which will still
917 // invalidate the entire array).
918 EvalCallOptions CallOpts;
919 Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
920 CallOpts.IsArrayCtorOrDtor).getAsRegion();
921
922 VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
923 Pred, Dst, CallOpts);
924 }
925
ProcessDeleteDtor(const CFGDeleteDtor Dtor,ExplodedNode * Pred,ExplodedNodeSet & Dst)926 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
927 ExplodedNode *Pred,
928 ExplodedNodeSet &Dst) {
929 ProgramStateRef State = Pred->getState();
930 const LocationContext *LCtx = Pred->getLocationContext();
931 const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
932 const Stmt *Arg = DE->getArgument();
933 QualType DTy = DE->getDestroyedType();
934 SVal ArgVal = State->getSVal(Arg, LCtx);
935
936 // If the argument to delete is known to be a null value,
937 // don't run destructor.
938 if (State->isNull(ArgVal).isConstrainedTrue()) {
939 QualType BTy = getContext().getBaseElementType(DTy);
940 const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
941 const CXXDestructorDecl *Dtor = RD->getDestructor();
942
943 PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
944 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
945 Bldr.generateNode(PP, Pred->getState(), Pred);
946 return;
947 }
948
949 EvalCallOptions CallOpts;
950 const MemRegion *ArgR = ArgVal.getAsRegion();
951 if (DE->isArrayForm()) {
952 // FIXME: We need to run the same destructor on every element of the array.
953 // This workaround will just run the first destructor (which will still
954 // invalidate the entire array).
955 CallOpts.IsArrayCtorOrDtor = true;
956 // Yes, it may even be a multi-dimensional array.
957 while (const auto *AT = getContext().getAsArrayType(DTy))
958 DTy = AT->getElementType();
959 if (ArgR)
960 ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
961 }
962
963 VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
964 }
965
ProcessBaseDtor(const CFGBaseDtor D,ExplodedNode * Pred,ExplodedNodeSet & Dst)966 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
967 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
968 const LocationContext *LCtx = Pred->getLocationContext();
969
970 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
971 Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
972 LCtx->getStackFrame());
973 SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
974
975 // Create the base object region.
976 const CXXBaseSpecifier *Base = D.getBaseSpecifier();
977 QualType BaseTy = Base->getType();
978 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
979 Base->isVirtual());
980
981 VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
982 CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
983 }
984
ProcessMemberDtor(const CFGMemberDtor D,ExplodedNode * Pred,ExplodedNodeSet & Dst)985 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
986 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
987 const FieldDecl *Member = D.getFieldDecl();
988 QualType T = Member->getType();
989 ProgramStateRef State = Pred->getState();
990 const LocationContext *LCtx = Pred->getLocationContext();
991
992 const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
993 Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
994 LCtx->getStackFrame());
995 SVal FieldVal =
996 State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
997
998 // FIXME: We need to run the same destructor on every element of the array.
999 // This workaround will just run the first destructor (which will still
1000 // invalidate the entire array).
1001 EvalCallOptions CallOpts;
1002 FieldVal = makeZeroElementRegion(State, FieldVal, T,
1003 CallOpts.IsArrayCtorOrDtor);
1004
1005 VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(),
1006 CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
1007 }
1008
ProcessTemporaryDtor(const CFGTemporaryDtor D,ExplodedNode * Pred,ExplodedNodeSet & Dst)1009 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
1010 ExplodedNode *Pred,
1011 ExplodedNodeSet &Dst) {
1012 const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
1013 ProgramStateRef State = Pred->getState();
1014 const LocationContext *LC = Pred->getLocationContext();
1015 const MemRegion *MR = nullptr;
1016
1017 if (Optional<SVal> V =
1018 getObjectUnderConstruction(State, D.getBindTemporaryExpr(),
1019 Pred->getLocationContext())) {
1020 // FIXME: Currently we insert temporary destructors for default parameters,
1021 // but we don't insert the constructors, so the entry in
1022 // ObjectsUnderConstruction may be missing.
1023 State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
1024 Pred->getLocationContext());
1025 MR = V->getAsRegion();
1026 }
1027
1028 // If copy elision has occured, and the constructor corresponding to the
1029 // destructor was elided, we need to skip the destructor as well.
1030 if (isDestructorElided(State, BTE, LC)) {
1031 State = cleanupElidedDestructor(State, BTE, LC);
1032 NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1033 PostImplicitCall PP(D.getDestructorDecl(getContext()),
1034 D.getBindTemporaryExpr()->getLocStart(),
1035 Pred->getLocationContext());
1036 Bldr.generateNode(PP, State, Pred);
1037 return;
1038 }
1039
1040 ExplodedNodeSet CleanDtorState;
1041 StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
1042 StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
1043
1044 QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType();
1045 // FIXME: Currently CleanDtorState can be empty here due to temporaries being
1046 // bound to default parameters.
1047 assert(CleanDtorState.size() <= 1);
1048 ExplodedNode *CleanPred =
1049 CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
1050
1051 EvalCallOptions CallOpts;
1052 CallOpts.IsTemporaryCtorOrDtor = true;
1053 if (!MR) {
1054 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
1055
1056 // If we have no MR, we still need to unwrap the array to avoid destroying
1057 // the whole array at once. Regardless, we'd eventually need to model array
1058 // destructors properly, element-by-element.
1059 while (const ArrayType *AT = getContext().getAsArrayType(T)) {
1060 T = AT->getElementType();
1061 CallOpts.IsArrayCtorOrDtor = true;
1062 }
1063 } else {
1064 // We'd eventually need to makeZeroElementRegion() trick here,
1065 // but for now we don't have the respective construction contexts,
1066 // so MR would always be null in this case. Do nothing for now.
1067 }
1068 VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(),
1069 /*IsBase=*/false, CleanPred, Dst, CallOpts);
1070 }
1071
processCleanupTemporaryBranch(const CXXBindTemporaryExpr * BTE,NodeBuilderContext & BldCtx,ExplodedNode * Pred,ExplodedNodeSet & Dst,const CFGBlock * DstT,const CFGBlock * DstF)1072 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
1073 NodeBuilderContext &BldCtx,
1074 ExplodedNode *Pred,
1075 ExplodedNodeSet &Dst,
1076 const CFGBlock *DstT,
1077 const CFGBlock *DstF) {
1078 BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
1079 ProgramStateRef State = Pred->getState();
1080 const LocationContext *LC = Pred->getLocationContext();
1081 if (getObjectUnderConstruction(State, BTE, LC)) {
1082 TempDtorBuilder.markInfeasible(false);
1083 TempDtorBuilder.generateNode(State, true, Pred);
1084 } else {
1085 TempDtorBuilder.markInfeasible(true);
1086 TempDtorBuilder.generateNode(State, false, Pred);
1087 }
1088 }
1089
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * BTE,ExplodedNodeSet & PreVisit,ExplodedNodeSet & Dst)1090 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
1091 ExplodedNodeSet &PreVisit,
1092 ExplodedNodeSet &Dst) {
1093 // This is a fallback solution in case we didn't have a construction
1094 // context when we were constructing the temporary. Otherwise the map should
1095 // have been populated there.
1096 if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
1097 // In case we don't have temporary destructors in the CFG, do not mark
1098 // the initialization - we would otherwise never clean it up.
1099 Dst = PreVisit;
1100 return;
1101 }
1102 StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
1103 for (ExplodedNode *Node : PreVisit) {
1104 ProgramStateRef State = Node->getState();
1105 const LocationContext *LC = Node->getLocationContext();
1106 if (!getObjectUnderConstruction(State, BTE, LC)) {
1107 // FIXME: Currently the state might also already contain the marker due to
1108 // incorrect handling of temporaries bound to default parameters; for
1109 // those, we currently skip the CXXBindTemporaryExpr but rely on adding
1110 // temporary destructor nodes.
1111 State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
1112 }
1113 StmtBldr.generateNode(BTE, Node, State);
1114 }
1115 }
1116
escapeValue(ProgramStateRef State,SVal V,PointerEscapeKind K) const1117 ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V,
1118 PointerEscapeKind K) const {
1119 class CollectReachableSymbolsCallback final : public SymbolVisitor {
1120 InvalidatedSymbols Symbols;
1121
1122 public:
1123 explicit CollectReachableSymbolsCallback(ProgramStateRef State) {}
1124
1125 const InvalidatedSymbols &getSymbols() const { return Symbols; }
1126
1127 bool VisitSymbol(SymbolRef Sym) override {
1128 Symbols.insert(Sym);
1129 return true;
1130 }
1131 };
1132
1133 const CollectReachableSymbolsCallback &Scanner =
1134 State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
1135 return getCheckerManager().runCheckersForPointerEscape(
1136 State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
1137 }
1138
Visit(const Stmt * S,ExplodedNode * Pred,ExplodedNodeSet & DstTop)1139 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
1140 ExplodedNodeSet &DstTop) {
1141 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1142 S->getLocStart(),
1143 "Error evaluating statement");
1144 ExplodedNodeSet Dst;
1145 StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
1146
1147 assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
1148
1149 switch (S->getStmtClass()) {
1150 // C++, OpenMP and ARC stuff we don't support yet.
1151 case Expr::ObjCIndirectCopyRestoreExprClass:
1152 case Stmt::CXXDependentScopeMemberExprClass:
1153 case Stmt::CXXInheritedCtorInitExprClass:
1154 case Stmt::CXXTryStmtClass:
1155 case Stmt::CXXTypeidExprClass:
1156 case Stmt::CXXUuidofExprClass:
1157 case Stmt::CXXFoldExprClass:
1158 case Stmt::MSPropertyRefExprClass:
1159 case Stmt::MSPropertySubscriptExprClass:
1160 case Stmt::CXXUnresolvedConstructExprClass:
1161 case Stmt::DependentScopeDeclRefExprClass:
1162 case Stmt::ArrayTypeTraitExprClass:
1163 case Stmt::ExpressionTraitExprClass:
1164 case Stmt::UnresolvedLookupExprClass:
1165 case Stmt::UnresolvedMemberExprClass:
1166 case Stmt::TypoExprClass:
1167 case Stmt::CXXNoexceptExprClass:
1168 case Stmt::PackExpansionExprClass:
1169 case Stmt::SubstNonTypeTemplateParmPackExprClass:
1170 case Stmt::FunctionParmPackExprClass:
1171 case Stmt::CoroutineBodyStmtClass:
1172 case Stmt::CoawaitExprClass:
1173 case Stmt::DependentCoawaitExprClass:
1174 case Stmt::CoreturnStmtClass:
1175 case Stmt::CoyieldExprClass:
1176 case Stmt::SEHTryStmtClass:
1177 case Stmt::SEHExceptStmtClass:
1178 case Stmt::SEHLeaveStmtClass:
1179 case Stmt::SEHFinallyStmtClass:
1180 case Stmt::OMPParallelDirectiveClass:
1181 case Stmt::OMPSimdDirectiveClass:
1182 case Stmt::OMPForDirectiveClass:
1183 case Stmt::OMPForSimdDirectiveClass:
1184 case Stmt::OMPSectionsDirectiveClass:
1185 case Stmt::OMPSectionDirectiveClass:
1186 case Stmt::OMPSingleDirectiveClass:
1187 case Stmt::OMPMasterDirectiveClass:
1188 case Stmt::OMPCriticalDirectiveClass:
1189 case Stmt::OMPParallelForDirectiveClass:
1190 case Stmt::OMPParallelForSimdDirectiveClass:
1191 case Stmt::OMPParallelSectionsDirectiveClass:
1192 case Stmt::OMPTaskDirectiveClass:
1193 case Stmt::OMPTaskyieldDirectiveClass:
1194 case Stmt::OMPBarrierDirectiveClass:
1195 case Stmt::OMPTaskwaitDirectiveClass:
1196 case Stmt::OMPTaskgroupDirectiveClass:
1197 case Stmt::OMPFlushDirectiveClass:
1198 case Stmt::OMPOrderedDirectiveClass:
1199 case Stmt::OMPAtomicDirectiveClass:
1200 case Stmt::OMPTargetDirectiveClass:
1201 case Stmt::OMPTargetDataDirectiveClass:
1202 case Stmt::OMPTargetEnterDataDirectiveClass:
1203 case Stmt::OMPTargetExitDataDirectiveClass:
1204 case Stmt::OMPTargetParallelDirectiveClass:
1205 case Stmt::OMPTargetParallelForDirectiveClass:
1206 case Stmt::OMPTargetUpdateDirectiveClass:
1207 case Stmt::OMPTeamsDirectiveClass:
1208 case Stmt::OMPCancellationPointDirectiveClass:
1209 case Stmt::OMPCancelDirectiveClass:
1210 case Stmt::OMPTaskLoopDirectiveClass:
1211 case Stmt::OMPTaskLoopSimdDirectiveClass:
1212 case Stmt::OMPDistributeDirectiveClass:
1213 case Stmt::OMPDistributeParallelForDirectiveClass:
1214 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1215 case Stmt::OMPDistributeSimdDirectiveClass:
1216 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1217 case Stmt::OMPTargetSimdDirectiveClass:
1218 case Stmt::OMPTeamsDistributeDirectiveClass:
1219 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1220 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1221 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1222 case Stmt::OMPTargetTeamsDirectiveClass:
1223 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1224 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1225 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1226 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1227 case Stmt::CapturedStmtClass: {
1228 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1229 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1230 break;
1231 }
1232
1233 case Stmt::ParenExprClass:
1234 llvm_unreachable("ParenExprs already handled.");
1235 case Stmt::GenericSelectionExprClass:
1236 llvm_unreachable("GenericSelectionExprs already handled.");
1237 // Cases that should never be evaluated simply because they shouldn't
1238 // appear in the CFG.
1239 case Stmt::BreakStmtClass:
1240 case Stmt::CaseStmtClass:
1241 case Stmt::CompoundStmtClass:
1242 case Stmt::ContinueStmtClass:
1243 case Stmt::CXXForRangeStmtClass:
1244 case Stmt::DefaultStmtClass:
1245 case Stmt::DoStmtClass:
1246 case Stmt::ForStmtClass:
1247 case Stmt::GotoStmtClass:
1248 case Stmt::IfStmtClass:
1249 case Stmt::IndirectGotoStmtClass:
1250 case Stmt::LabelStmtClass:
1251 case Stmt::NoStmtClass:
1252 case Stmt::NullStmtClass:
1253 case Stmt::SwitchStmtClass:
1254 case Stmt::WhileStmtClass:
1255 case Expr::MSDependentExistsStmtClass:
1256 llvm_unreachable("Stmt should not be in analyzer evaluation loop");
1257
1258 case Stmt::ObjCSubscriptRefExprClass:
1259 case Stmt::ObjCPropertyRefExprClass:
1260 llvm_unreachable("These are handled by PseudoObjectExpr");
1261
1262 case Stmt::GNUNullExprClass: {
1263 // GNU __null is a pointer-width integer, not an actual pointer.
1264 ProgramStateRef state = Pred->getState();
1265 state = state->BindExpr(S, Pred->getLocationContext(),
1266 svalBuilder.makeIntValWithPtrWidth(0, false));
1267 Bldr.generateNode(S, Pred, state);
1268 break;
1269 }
1270
1271 case Stmt::ObjCAtSynchronizedStmtClass:
1272 Bldr.takeNodes(Pred);
1273 VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
1274 Bldr.addNodes(Dst);
1275 break;
1276
1277 case Stmt::ExprWithCleanupsClass:
1278 // Handled due to fully linearised CFG.
1279 break;
1280
1281 case Stmt::CXXBindTemporaryExprClass: {
1282 Bldr.takeNodes(Pred);
1283 ExplodedNodeSet PreVisit;
1284 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1285 ExplodedNodeSet Next;
1286 VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
1287 getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
1288 Bldr.addNodes(Dst);
1289 break;
1290 }
1291
1292 // Cases not handled yet; but will handle some day.
1293 case Stmt::DesignatedInitExprClass:
1294 case Stmt::DesignatedInitUpdateExprClass:
1295 case Stmt::ArrayInitLoopExprClass:
1296 case Stmt::ArrayInitIndexExprClass:
1297 case Stmt::ExtVectorElementExprClass:
1298 case Stmt::ImaginaryLiteralClass:
1299 case Stmt::ObjCAtCatchStmtClass:
1300 case Stmt::ObjCAtFinallyStmtClass:
1301 case Stmt::ObjCAtTryStmtClass:
1302 case Stmt::ObjCAutoreleasePoolStmtClass:
1303 case Stmt::ObjCEncodeExprClass:
1304 case Stmt::ObjCIsaExprClass:
1305 case Stmt::ObjCProtocolExprClass:
1306 case Stmt::ObjCSelectorExprClass:
1307 case Stmt::ParenListExprClass:
1308 case Stmt::ShuffleVectorExprClass:
1309 case Stmt::ConvertVectorExprClass:
1310 case Stmt::VAArgExprClass:
1311 case Stmt::CUDAKernelCallExprClass:
1312 case Stmt::OpaqueValueExprClass:
1313 case Stmt::AsTypeExprClass:
1314 // Fall through.
1315
1316 // Cases we intentionally don't evaluate, since they don't need
1317 // to be explicitly evaluated.
1318 case Stmt::PredefinedExprClass:
1319 case Stmt::AddrLabelExprClass:
1320 case Stmt::AttributedStmtClass:
1321 case Stmt::IntegerLiteralClass:
1322 case Stmt::FixedPointLiteralClass:
1323 case Stmt::CharacterLiteralClass:
1324 case Stmt::ImplicitValueInitExprClass:
1325 case Stmt::CXXScalarValueInitExprClass:
1326 case Stmt::CXXBoolLiteralExprClass:
1327 case Stmt::ObjCBoolLiteralExprClass:
1328 case Stmt::ObjCAvailabilityCheckExprClass:
1329 case Stmt::FloatingLiteralClass:
1330 case Stmt::NoInitExprClass:
1331 case Stmt::SizeOfPackExprClass:
1332 case Stmt::StringLiteralClass:
1333 case Stmt::ObjCStringLiteralClass:
1334 case Stmt::CXXPseudoDestructorExprClass:
1335 case Stmt::SubstNonTypeTemplateParmExprClass:
1336 case Stmt::CXXNullPtrLiteralExprClass:
1337 case Stmt::OMPArraySectionExprClass:
1338 case Stmt::TypeTraitExprClass: {
1339 Bldr.takeNodes(Pred);
1340 ExplodedNodeSet preVisit;
1341 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1342 getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1343 Bldr.addNodes(Dst);
1344 break;
1345 }
1346
1347 case Stmt::CXXDefaultArgExprClass:
1348 case Stmt::CXXDefaultInitExprClass: {
1349 Bldr.takeNodes(Pred);
1350 ExplodedNodeSet PreVisit;
1351 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1352
1353 ExplodedNodeSet Tmp;
1354 StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1355
1356 const Expr *ArgE;
1357 if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1358 ArgE = DefE->getExpr();
1359 else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1360 ArgE = DefE->getExpr();
1361 else
1362 llvm_unreachable("unknown constant wrapper kind");
1363
1364 bool IsTemporary = false;
1365 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1366 ArgE = MTE->GetTemporaryExpr();
1367 IsTemporary = true;
1368 }
1369
1370 Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1371 if (!ConstantVal)
1372 ConstantVal = UnknownVal();
1373
1374 const LocationContext *LCtx = Pred->getLocationContext();
1375 for (const auto I : PreVisit) {
1376 ProgramStateRef State = I->getState();
1377 State = State->BindExpr(S, LCtx, *ConstantVal);
1378 if (IsTemporary)
1379 State = createTemporaryRegionIfNeeded(State, LCtx,
1380 cast<Expr>(S),
1381 cast<Expr>(S));
1382 Bldr2.generateNode(S, I, State);
1383 }
1384
1385 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1386 Bldr.addNodes(Dst);
1387 break;
1388 }
1389
1390 // Cases we evaluate as opaque expressions, conjuring a symbol.
1391 case Stmt::CXXStdInitializerListExprClass:
1392 case Expr::ObjCArrayLiteralClass:
1393 case Expr::ObjCDictionaryLiteralClass:
1394 case Expr::ObjCBoxedExprClass: {
1395 Bldr.takeNodes(Pred);
1396
1397 ExplodedNodeSet preVisit;
1398 getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1399
1400 ExplodedNodeSet Tmp;
1401 StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
1402
1403 const auto *Ex = cast<Expr>(S);
1404 QualType resultType = Ex->getType();
1405
1406 for (const auto N : preVisit) {
1407 const LocationContext *LCtx = N->getLocationContext();
1408 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1409 resultType,
1410 currBldrCtx->blockCount());
1411 ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
1412
1413 // Escape pointers passed into the list, unless it's an ObjC boxed
1414 // expression which is not a boxable C structure.
1415 if (!(isa<ObjCBoxedExpr>(Ex) &&
1416 !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
1417 ->getType()->isRecordType()))
1418 for (auto Child : Ex->children()) {
1419 assert(Child);
1420 SVal Val = State->getSVal(Child, LCtx);
1421 State = escapeValue(State, Val, PSK_EscapeOther);
1422 }
1423
1424 Bldr2.generateNode(S, N, State);
1425 }
1426
1427 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1428 Bldr.addNodes(Dst);
1429 break;
1430 }
1431
1432 case Stmt::ArraySubscriptExprClass:
1433 Bldr.takeNodes(Pred);
1434 VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1435 Bldr.addNodes(Dst);
1436 break;
1437
1438 case Stmt::GCCAsmStmtClass:
1439 Bldr.takeNodes(Pred);
1440 VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1441 Bldr.addNodes(Dst);
1442 break;
1443
1444 case Stmt::MSAsmStmtClass:
1445 Bldr.takeNodes(Pred);
1446 VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1447 Bldr.addNodes(Dst);
1448 break;
1449
1450 case Stmt::BlockExprClass:
1451 Bldr.takeNodes(Pred);
1452 VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1453 Bldr.addNodes(Dst);
1454 break;
1455
1456 case Stmt::LambdaExprClass:
1457 if (AMgr.options.shouldInlineLambdas()) {
1458 Bldr.takeNodes(Pred);
1459 VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1460 Bldr.addNodes(Dst);
1461 } else {
1462 const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1463 Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1464 }
1465 break;
1466
1467 case Stmt::BinaryOperatorClass: {
1468 const auto *B = cast<BinaryOperator>(S);
1469 if (B->isLogicalOp()) {
1470 Bldr.takeNodes(Pred);
1471 VisitLogicalExpr(B, Pred, Dst);
1472 Bldr.addNodes(Dst);
1473 break;
1474 }
1475 else if (B->getOpcode() == BO_Comma) {
1476 ProgramStateRef state = Pred->getState();
1477 Bldr.generateNode(B, Pred,
1478 state->BindExpr(B, Pred->getLocationContext(),
1479 state->getSVal(B->getRHS(),
1480 Pred->getLocationContext())));
1481 break;
1482 }
1483
1484 Bldr.takeNodes(Pred);
1485
1486 if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
1487 (B->isRelationalOp() || B->isEqualityOp())) {
1488 ExplodedNodeSet Tmp;
1489 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1490 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1491 }
1492 else
1493 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1494
1495 Bldr.addNodes(Dst);
1496 break;
1497 }
1498
1499 case Stmt::CXXOperatorCallExprClass: {
1500 const auto *OCE = cast<CXXOperatorCallExpr>(S);
1501
1502 // For instance method operators, make sure the 'this' argument has a
1503 // valid region.
1504 const Decl *Callee = OCE->getCalleeDecl();
1505 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1506 if (MD->isInstance()) {
1507 ProgramStateRef State = Pred->getState();
1508 const LocationContext *LCtx = Pred->getLocationContext();
1509 ProgramStateRef NewState =
1510 createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1511 if (NewState != State) {
1512 Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1513 ProgramPoint::PreStmtKind);
1514 // Did we cache out?
1515 if (!Pred)
1516 break;
1517 }
1518 }
1519 }
1520 // FALLTHROUGH
1521 LLVM_FALLTHROUGH;
1522 }
1523
1524 case Stmt::CallExprClass:
1525 case Stmt::CXXMemberCallExprClass:
1526 case Stmt::UserDefinedLiteralClass:
1527 Bldr.takeNodes(Pred);
1528 VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1529 Bldr.addNodes(Dst);
1530 break;
1531
1532 case Stmt::CXXCatchStmtClass:
1533 Bldr.takeNodes(Pred);
1534 VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1535 Bldr.addNodes(Dst);
1536 break;
1537
1538 case Stmt::CXXTemporaryObjectExprClass:
1539 case Stmt::CXXConstructExprClass:
1540 Bldr.takeNodes(Pred);
1541 VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1542 Bldr.addNodes(Dst);
1543 break;
1544
1545 case Stmt::CXXNewExprClass: {
1546 Bldr.takeNodes(Pred);
1547
1548 ExplodedNodeSet PreVisit;
1549 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1550
1551 ExplodedNodeSet PostVisit;
1552 for (const auto i : PreVisit)
1553 VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
1554
1555 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1556 Bldr.addNodes(Dst);
1557 break;
1558 }
1559
1560 case Stmt::CXXDeleteExprClass: {
1561 Bldr.takeNodes(Pred);
1562 ExplodedNodeSet PreVisit;
1563 const auto *CDE = cast<CXXDeleteExpr>(S);
1564 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1565
1566 for (const auto i : PreVisit)
1567 VisitCXXDeleteExpr(CDE, i, Dst);
1568
1569 Bldr.addNodes(Dst);
1570 break;
1571 }
1572 // FIXME: ChooseExpr is really a constant. We need to fix
1573 // the CFG do not model them as explicit control-flow.
1574
1575 case Stmt::ChooseExprClass: { // __builtin_choose_expr
1576 Bldr.takeNodes(Pred);
1577 const auto *C = cast<ChooseExpr>(S);
1578 VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1579 Bldr.addNodes(Dst);
1580 break;
1581 }
1582
1583 case Stmt::CompoundAssignOperatorClass:
1584 Bldr.takeNodes(Pred);
1585 VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1586 Bldr.addNodes(Dst);
1587 break;
1588
1589 case Stmt::CompoundLiteralExprClass:
1590 Bldr.takeNodes(Pred);
1591 VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1592 Bldr.addNodes(Dst);
1593 break;
1594
1595 case Stmt::BinaryConditionalOperatorClass:
1596 case Stmt::ConditionalOperatorClass: { // '?' operator
1597 Bldr.takeNodes(Pred);
1598 const auto *C = cast<AbstractConditionalOperator>(S);
1599 VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1600 Bldr.addNodes(Dst);
1601 break;
1602 }
1603
1604 case Stmt::CXXThisExprClass:
1605 Bldr.takeNodes(Pred);
1606 VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1607 Bldr.addNodes(Dst);
1608 break;
1609
1610 case Stmt::DeclRefExprClass: {
1611 Bldr.takeNodes(Pred);
1612 const auto *DE = cast<DeclRefExpr>(S);
1613 VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1614 Bldr.addNodes(Dst);
1615 break;
1616 }
1617
1618 case Stmt::DeclStmtClass:
1619 Bldr.takeNodes(Pred);
1620 VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1621 Bldr.addNodes(Dst);
1622 break;
1623
1624 case Stmt::ImplicitCastExprClass:
1625 case Stmt::CStyleCastExprClass:
1626 case Stmt::CXXStaticCastExprClass:
1627 case Stmt::CXXDynamicCastExprClass:
1628 case Stmt::CXXReinterpretCastExprClass:
1629 case Stmt::CXXConstCastExprClass:
1630 case Stmt::CXXFunctionalCastExprClass:
1631 case Stmt::ObjCBridgedCastExprClass: {
1632 Bldr.takeNodes(Pred);
1633 const auto *C = cast<CastExpr>(S);
1634 ExplodedNodeSet dstExpr;
1635 VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1636
1637 // Handle the postvisit checks.
1638 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1639 Bldr.addNodes(Dst);
1640 break;
1641 }
1642
1643 case Expr::MaterializeTemporaryExprClass: {
1644 Bldr.takeNodes(Pred);
1645 const auto *MTE = cast<MaterializeTemporaryExpr>(S);
1646 ExplodedNodeSet dstPrevisit;
1647 getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1648 ExplodedNodeSet dstExpr;
1649 for (const auto i : dstPrevisit)
1650 CreateCXXTemporaryObject(MTE, i, dstExpr);
1651 getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1652 Bldr.addNodes(Dst);
1653 break;
1654 }
1655
1656 case Stmt::InitListExprClass:
1657 Bldr.takeNodes(Pred);
1658 VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1659 Bldr.addNodes(Dst);
1660 break;
1661
1662 case Stmt::MemberExprClass:
1663 Bldr.takeNodes(Pred);
1664 VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1665 Bldr.addNodes(Dst);
1666 break;
1667
1668 case Stmt::AtomicExprClass:
1669 Bldr.takeNodes(Pred);
1670 VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1671 Bldr.addNodes(Dst);
1672 break;
1673
1674 case Stmt::ObjCIvarRefExprClass:
1675 Bldr.takeNodes(Pred);
1676 VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1677 Bldr.addNodes(Dst);
1678 break;
1679
1680 case Stmt::ObjCForCollectionStmtClass:
1681 Bldr.takeNodes(Pred);
1682 VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1683 Bldr.addNodes(Dst);
1684 break;
1685
1686 case Stmt::ObjCMessageExprClass:
1687 Bldr.takeNodes(Pred);
1688 VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1689 Bldr.addNodes(Dst);
1690 break;
1691
1692 case Stmt::ObjCAtThrowStmtClass:
1693 case Stmt::CXXThrowExprClass:
1694 // FIXME: This is not complete. We basically treat @throw as
1695 // an abort.
1696 Bldr.generateSink(S, Pred, Pred->getState());
1697 break;
1698
1699 case Stmt::ReturnStmtClass:
1700 Bldr.takeNodes(Pred);
1701 VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1702 Bldr.addNodes(Dst);
1703 break;
1704
1705 case Stmt::OffsetOfExprClass: {
1706 Bldr.takeNodes(Pred);
1707 ExplodedNodeSet PreVisit;
1708 getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1709
1710 ExplodedNodeSet PostVisit;
1711 for (const auto Node : PreVisit)
1712 VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
1713
1714 getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1715 Bldr.addNodes(Dst);
1716 break;
1717 }
1718
1719 case Stmt::UnaryExprOrTypeTraitExprClass:
1720 Bldr.takeNodes(Pred);
1721 VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1722 Pred, Dst);
1723 Bldr.addNodes(Dst);
1724 break;
1725
1726 case Stmt::StmtExprClass: {
1727 const auto *SE = cast<StmtExpr>(S);
1728
1729 if (SE->getSubStmt()->body_empty()) {
1730 // Empty statement expression.
1731 assert(SE->getType() == getContext().VoidTy
1732 && "Empty statement expression must have void type.");
1733 break;
1734 }
1735
1736 if (const auto *LastExpr =
1737 dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1738 ProgramStateRef state = Pred->getState();
1739 Bldr.generateNode(SE, Pred,
1740 state->BindExpr(SE, Pred->getLocationContext(),
1741 state->getSVal(LastExpr,
1742 Pred->getLocationContext())));
1743 }
1744 break;
1745 }
1746
1747 case Stmt::UnaryOperatorClass: {
1748 Bldr.takeNodes(Pred);
1749 const auto *U = cast<UnaryOperator>(S);
1750 if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
1751 ExplodedNodeSet Tmp;
1752 VisitUnaryOperator(U, Pred, Tmp);
1753 evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1754 }
1755 else
1756 VisitUnaryOperator(U, Pred, Dst);
1757 Bldr.addNodes(Dst);
1758 break;
1759 }
1760
1761 case Stmt::PseudoObjectExprClass: {
1762 Bldr.takeNodes(Pred);
1763 ProgramStateRef state = Pred->getState();
1764 const auto *PE = cast<PseudoObjectExpr>(S);
1765 if (const Expr *Result = PE->getResultExpr()) {
1766 SVal V = state->getSVal(Result, Pred->getLocationContext());
1767 Bldr.generateNode(S, Pred,
1768 state->BindExpr(S, Pred->getLocationContext(), V));
1769 }
1770 else
1771 Bldr.generateNode(S, Pred,
1772 state->BindExpr(S, Pred->getLocationContext(),
1773 UnknownVal()));
1774
1775 Bldr.addNodes(Dst);
1776 break;
1777 }
1778 }
1779 }
1780
replayWithoutInlining(ExplodedNode * N,const LocationContext * CalleeLC)1781 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1782 const LocationContext *CalleeLC) {
1783 const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
1784 const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
1785 assert(CalleeSF && CallerSF);
1786 ExplodedNode *BeforeProcessingCall = nullptr;
1787 const Stmt *CE = CalleeSF->getCallSite();
1788
1789 // Find the first node before we started processing the call expression.
1790 while (N) {
1791 ProgramPoint L = N->getLocation();
1792 BeforeProcessingCall = N;
1793 N = N->pred_empty() ? nullptr : *(N->pred_begin());
1794
1795 // Skip the nodes corresponding to the inlined code.
1796 if (L.getStackFrame() != CallerSF)
1797 continue;
1798 // We reached the caller. Find the node right before we started
1799 // processing the call.
1800 if (L.isPurgeKind())
1801 continue;
1802 if (L.getAs<PreImplicitCall>())
1803 continue;
1804 if (L.getAs<CallEnter>())
1805 continue;
1806 if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1807 if (SP->getStmt() == CE)
1808 continue;
1809 break;
1810 }
1811
1812 if (!BeforeProcessingCall)
1813 return false;
1814
1815 // TODO: Clean up the unneeded nodes.
1816
1817 // Build an Epsilon node from which we will restart the analyzes.
1818 // Note that CE is permitted to be NULL!
1819 ProgramPoint NewNodeLoc =
1820 EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1821 // Add the special flag to GDM to signal retrying with no inlining.
1822 // Note, changing the state ensures that we are not going to cache out.
1823 ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1824 NewNodeState =
1825 NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1826
1827 // Make the new node a successor of BeforeProcessingCall.
1828 bool IsNew = false;
1829 ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1830 // We cached out at this point. Caching out is common due to us backtracking
1831 // from the inlined function, which might spawn several paths.
1832 if (!IsNew)
1833 return true;
1834
1835 NewNode->addPredecessor(BeforeProcessingCall, G);
1836
1837 // Add the new node to the work list.
1838 Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1839 CalleeSF->getIndex());
1840 NumTimesRetriedWithoutInlining++;
1841 return true;
1842 }
1843
1844 /// Block entrance. (Update counters).
processCFGBlockEntrance(const BlockEdge & L,NodeBuilderWithSinks & nodeBuilder,ExplodedNode * Pred)1845 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1846 NodeBuilderWithSinks &nodeBuilder,
1847 ExplodedNode *Pred) {
1848 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1849 // If we reach a loop which has a known bound (and meets
1850 // other constraints) then consider completely unrolling it.
1851 if(AMgr.options.shouldUnrollLoops()) {
1852 unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
1853 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1854 if (Term) {
1855 ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
1856 Pred, maxBlockVisitOnPath);
1857 if (NewState != Pred->getState()) {
1858 ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
1859 if (!UpdatedNode)
1860 return;
1861 Pred = UpdatedNode;
1862 }
1863 }
1864 // Is we are inside an unrolled loop then no need the check the counters.
1865 if(isUnrolledState(Pred->getState()))
1866 return;
1867 }
1868
1869 // If this block is terminated by a loop and it has already been visited the
1870 // maximum number of times, widen the loop.
1871 unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1872 if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1873 AMgr.options.shouldWidenLoops()) {
1874 const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1875 if (!(Term &&
1876 (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1877 return;
1878 // Widen.
1879 const LocationContext *LCtx = Pred->getLocationContext();
1880 ProgramStateRef WidenedState =
1881 getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1882 nodeBuilder.generateNode(WidenedState, Pred);
1883 return;
1884 }
1885
1886 // FIXME: Refactor this into a checker.
1887 if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1888 static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1889 const ExplodedNode *Sink =
1890 nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1891
1892 // Check if we stopped at the top level function or not.
1893 // Root node should have the location context of the top most function.
1894 const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1895 const LocationContext *CalleeSF = CalleeLC->getStackFrame();
1896 const LocationContext *RootLC =
1897 (*G.roots_begin())->getLocation().getLocationContext();
1898 if (RootLC->getStackFrame() != CalleeSF) {
1899 Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1900
1901 // Re-run the call evaluation without inlining it, by storing the
1902 // no-inlining policy in the state and enqueuing the new work item on
1903 // the list. Replay should almost never fail. Use the stats to catch it
1904 // if it does.
1905 if ((!AMgr.options.NoRetryExhausted &&
1906 replayWithoutInlining(Pred, CalleeLC)))
1907 return;
1908 NumMaxBlockCountReachedInInlined++;
1909 } else
1910 NumMaxBlockCountReached++;
1911
1912 // Make sink nodes as exhausted(for stats) only if retry failed.
1913 Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1914 }
1915 }
1916
1917 //===----------------------------------------------------------------------===//
1918 // Branch processing.
1919 //===----------------------------------------------------------------------===//
1920
1921 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1922 /// to try to recover some path-sensitivity for casts of symbolic
1923 /// integers that promote their values (which are currently not tracked well).
1924 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1925 // cast(s) did was sign-extend the original value.
RecoverCastedSymbol(ProgramStateManager & StateMgr,ProgramStateRef state,const Stmt * Condition,const LocationContext * LCtx,ASTContext & Ctx)1926 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
1927 ProgramStateRef state,
1928 const Stmt *Condition,
1929 const LocationContext *LCtx,
1930 ASTContext &Ctx) {
1931
1932 const auto *Ex = dyn_cast<Expr>(Condition);
1933 if (!Ex)
1934 return UnknownVal();
1935
1936 uint64_t bits = 0;
1937 bool bitsInit = false;
1938
1939 while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
1940 QualType T = CE->getType();
1941
1942 if (!T->isIntegralOrEnumerationType())
1943 return UnknownVal();
1944
1945 uint64_t newBits = Ctx.getTypeSize(T);
1946 if (!bitsInit || newBits < bits) {
1947 bitsInit = true;
1948 bits = newBits;
1949 }
1950
1951 Ex = CE->getSubExpr();
1952 }
1953
1954 // We reached a non-cast. Is it a symbolic value?
1955 QualType T = Ex->getType();
1956
1957 if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1958 Ctx.getTypeSize(T) > bits)
1959 return UnknownVal();
1960
1961 return state->getSVal(Ex, LCtx);
1962 }
1963
1964 #ifndef NDEBUG
getRightmostLeaf(const Stmt * Condition)1965 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1966 while (Condition) {
1967 const auto *BO = dyn_cast<BinaryOperator>(Condition);
1968 if (!BO || !BO->isLogicalOp()) {
1969 return Condition;
1970 }
1971 Condition = BO->getRHS()->IgnoreParens();
1972 }
1973 return nullptr;
1974 }
1975 #endif
1976
1977 // Returns the condition the branch at the end of 'B' depends on and whose value
1978 // has been evaluated within 'B'.
1979 // In most cases, the terminator condition of 'B' will be evaluated fully in
1980 // the last statement of 'B'; in those cases, the resolved condition is the
1981 // given 'Condition'.
1982 // If the condition of the branch is a logical binary operator tree, the CFG is
1983 // optimized: in that case, we know that the expression formed by all but the
1984 // rightmost leaf of the logical binary operator tree must be true, and thus
1985 // the branch condition is at this point equivalent to the truth value of that
1986 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1987 // expression in its final statement. As the full condition in that case was
1988 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1989 // expression to evaluate the truth value of the condition in the current state
1990 // space.
ResolveCondition(const Stmt * Condition,const CFGBlock * B)1991 static const Stmt *ResolveCondition(const Stmt *Condition,
1992 const CFGBlock *B) {
1993 if (const auto *Ex = dyn_cast<Expr>(Condition))
1994 Condition = Ex->IgnoreParens();
1995
1996 const auto *BO = dyn_cast<BinaryOperator>(Condition);
1997 if (!BO || !BO->isLogicalOp())
1998 return Condition;
1999
2000 assert(!B->getTerminator().isTemporaryDtorsBranch() &&
2001 "Temporary destructor branches handled by processBindTemporary.");
2002
2003 // For logical operations, we still have the case where some branches
2004 // use the traditional "merge" approach and others sink the branch
2005 // directly into the basic blocks representing the logical operation.
2006 // We need to distinguish between those two cases here.
2007
2008 // The invariants are still shifting, but it is possible that the
2009 // last element in a CFGBlock is not a CFGStmt. Look for the last
2010 // CFGStmt as the value of the condition.
2011 CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
2012 for (; I != E; ++I) {
2013 CFGElement Elem = *I;
2014 Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
2015 if (!CS)
2016 continue;
2017 const Stmt *LastStmt = CS->getStmt();
2018 assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
2019 return LastStmt;
2020 }
2021 llvm_unreachable("could not resolve condition");
2022 }
2023
processBranch(const Stmt * Condition,const Stmt * Term,NodeBuilderContext & BldCtx,ExplodedNode * Pred,ExplodedNodeSet & Dst,const CFGBlock * DstT,const CFGBlock * DstF)2024 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
2025 NodeBuilderContext& BldCtx,
2026 ExplodedNode *Pred,
2027 ExplodedNodeSet &Dst,
2028 const CFGBlock *DstT,
2029 const CFGBlock *DstF) {
2030 assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
2031 "CXXBindTemporaryExprs are handled by processBindTemporary.");
2032 const LocationContext *LCtx = Pred->getLocationContext();
2033 PrettyStackTraceLocationContext StackCrashInfo(LCtx);
2034 currBldrCtx = &BldCtx;
2035
2036 // Check for NULL conditions; e.g. "for(;;)"
2037 if (!Condition) {
2038 BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
2039 NullCondBldr.markInfeasible(false);
2040 NullCondBldr.generateNode(Pred->getState(), true, Pred);
2041 return;
2042 }
2043
2044 if (const auto *Ex = dyn_cast<Expr>(Condition))
2045 Condition = Ex->IgnoreParens();
2046
2047 Condition = ResolveCondition(Condition, BldCtx.getBlock());
2048 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
2049 Condition->getLocStart(),
2050 "Error evaluating branch");
2051
2052 ExplodedNodeSet CheckersOutSet;
2053 getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
2054 Pred, *this);
2055 // We generated only sinks.
2056 if (CheckersOutSet.empty())
2057 return;
2058
2059 BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
2060 for (const auto PredI : CheckersOutSet) {
2061 if (PredI->isSink())
2062 continue;
2063
2064 ProgramStateRef PrevState = PredI->getState();
2065 SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
2066
2067 if (X.isUnknownOrUndef()) {
2068 // Give it a chance to recover from unknown.
2069 if (const auto *Ex = dyn_cast<Expr>(Condition)) {
2070 if (Ex->getType()->isIntegralOrEnumerationType()) {
2071 // Try to recover some path-sensitivity. Right now casts of symbolic
2072 // integers that promote their values are currently not tracked well.
2073 // If 'Condition' is such an expression, try and recover the
2074 // underlying value and use that instead.
2075 SVal recovered = RecoverCastedSymbol(getStateManager(),
2076 PrevState, Condition,
2077 PredI->getLocationContext(),
2078 getContext());
2079
2080 if (!recovered.isUnknown()) {
2081 X = recovered;
2082 }
2083 }
2084 }
2085 }
2086
2087 // If the condition is still unknown, give up.
2088 if (X.isUnknownOrUndef()) {
2089 builder.generateNode(PrevState, true, PredI);
2090 builder.generateNode(PrevState, false, PredI);
2091 continue;
2092 }
2093
2094 DefinedSVal V = X.castAs<DefinedSVal>();
2095
2096 ProgramStateRef StTrue, StFalse;
2097 std::tie(StTrue, StFalse) = PrevState->assume(V);
2098
2099 // Process the true branch.
2100 if (builder.isFeasible(true)) {
2101 if (StTrue)
2102 builder.generateNode(StTrue, true, PredI);
2103 else
2104 builder.markInfeasible(true);
2105 }
2106
2107 // Process the false branch.
2108 if (builder.isFeasible(false)) {
2109 if (StFalse)
2110 builder.generateNode(StFalse, false, PredI);
2111 else
2112 builder.markInfeasible(false);
2113 }
2114 }
2115 currBldrCtx = nullptr;
2116 }
2117
2118 /// The GDM component containing the set of global variables which have been
2119 /// previously initialized with explicit initializers.
REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,llvm::ImmutableSet<const VarDecl * >)2120 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
2121 llvm::ImmutableSet<const VarDecl *>)
2122
2123 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
2124 NodeBuilderContext &BuilderCtx,
2125 ExplodedNode *Pred,
2126 ExplodedNodeSet &Dst,
2127 const CFGBlock *DstT,
2128 const CFGBlock *DstF) {
2129 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
2130 currBldrCtx = &BuilderCtx;
2131
2132 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
2133 ProgramStateRef state = Pred->getState();
2134 bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
2135 BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
2136
2137 if (!initHasRun) {
2138 state = state->add<InitializedGlobalsSet>(VD);
2139 }
2140
2141 builder.generateNode(state, initHasRun, Pred);
2142 builder.markInfeasible(!initHasRun);
2143
2144 currBldrCtx = nullptr;
2145 }
2146
2147 /// processIndirectGoto - Called by CoreEngine. Used to generate successor
2148 /// nodes by processing the 'effects' of a computed goto jump.
processIndirectGoto(IndirectGotoNodeBuilder & builder)2149 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
2150 ProgramStateRef state = builder.getState();
2151 SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
2152
2153 // Three possibilities:
2154 //
2155 // (1) We know the computed label.
2156 // (2) The label is NULL (or some other constant), or Undefined.
2157 // (3) We have no clue about the label. Dispatch to all targets.
2158 //
2159
2160 using iterator = IndirectGotoNodeBuilder::iterator;
2161
2162 if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
2163 const LabelDecl *L = LV->getLabel();
2164
2165 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
2166 if (I.getLabel() == L) {
2167 builder.generateNode(I, state);
2168 return;
2169 }
2170 }
2171
2172 llvm_unreachable("No block with label.");
2173 }
2174
2175 if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
2176 // Dispatch to the first target and mark it as a sink.
2177 //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
2178 // FIXME: add checker visit.
2179 // UndefBranches.insert(N);
2180 return;
2181 }
2182
2183 // This is really a catch-all. We don't support symbolics yet.
2184 // FIXME: Implement dispatch for symbolic pointers.
2185
2186 for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
2187 builder.generateNode(I, state);
2188 }
2189
processBeginOfFunction(NodeBuilderContext & BC,ExplodedNode * Pred,ExplodedNodeSet & Dst,const BlockEdge & L)2190 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
2191 ExplodedNode *Pred,
2192 ExplodedNodeSet &Dst,
2193 const BlockEdge &L) {
2194 SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
2195 getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
2196 }
2197
2198 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
2199 /// nodes when the control reaches the end of a function.
processEndOfFunction(NodeBuilderContext & BC,ExplodedNode * Pred,const ReturnStmt * RS)2200 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
2201 ExplodedNode *Pred,
2202 const ReturnStmt *RS) {
2203 // FIXME: We currently cannot assert that temporaries are clear, because
2204 // lifetime extended temporaries are not always modelled correctly. In some
2205 // cases when we materialize the temporary, we do
2206 // createTemporaryRegionIfNeeded(), and the region changes, and also the
2207 // respective destructor becomes automatic from temporary. So for now clean up
2208 // the state manually before asserting. Ideally, the code above the assertion
2209 // should go away, but the assertion should remain.
2210 {
2211 ExplodedNodeSet CleanUpObjects;
2212 NodeBuilder Bldr(Pred, CleanUpObjects, BC);
2213 ProgramStateRef State = Pred->getState();
2214 const LocationContext *FromLC = Pred->getLocationContext();
2215 const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
2216 const LocationContext *LC = FromLC;
2217 while (LC != ToLC) {
2218 assert(LC && "ToLC must be a parent of FromLC!");
2219 for (auto I : State->get<ObjectsUnderConstruction>())
2220 if (I.first.getLocationContext() == LC) {
2221 // The comment above only pardons us for not cleaning up a
2222 // temporary destructor. If any other statements are found here,
2223 // it must be a separate problem.
2224 assert(I.first.getItem().getKind() ==
2225 ConstructionContextItem::TemporaryDestructorKind ||
2226 I.first.getItem().getKind() ==
2227 ConstructionContextItem::ElidedDestructorKind);
2228 State = State->remove<ObjectsUnderConstruction>(I.first);
2229 }
2230 LC = LC->getParent();
2231 }
2232 if (State != Pred->getState()) {
2233 Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
2234 if (!Pred) {
2235 // The node with clean temporaries already exists. We might have reached
2236 // it on a path on which we initialize different temporaries.
2237 return;
2238 }
2239 }
2240 }
2241 assert(areAllObjectsFullyConstructed(Pred->getState(),
2242 Pred->getLocationContext(),
2243 Pred->getStackFrame()->getParent()));
2244
2245 PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
2246 StateMgr.EndPath(Pred->getState());
2247
2248 ExplodedNodeSet Dst;
2249 if (Pred->getLocationContext()->inTopFrame()) {
2250 // Remove dead symbols.
2251 ExplodedNodeSet AfterRemovedDead;
2252 removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
2253
2254 // Notify checkers.
2255 for (const auto I : AfterRemovedDead)
2256 getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS);
2257 } else {
2258 getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS);
2259 }
2260
2261 Engine.enqueueEndOfFunction(Dst, RS);
2262 }
2263
2264 /// ProcessSwitch - Called by CoreEngine. Used to generate successor
2265 /// nodes by processing the 'effects' of a switch statement.
processSwitch(SwitchNodeBuilder & builder)2266 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
2267 using iterator = SwitchNodeBuilder::iterator;
2268
2269 ProgramStateRef state = builder.getState();
2270 const Expr *CondE = builder.getCondition();
2271 SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
2272
2273 if (CondV_untested.isUndef()) {
2274 //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
2275 // FIXME: add checker
2276 //UndefBranches.insert(N);
2277
2278 return;
2279 }
2280 DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
2281
2282 ProgramStateRef DefaultSt = state;
2283
2284 iterator I = builder.begin(), EI = builder.end();
2285 bool defaultIsFeasible = I == EI;
2286
2287 for ( ; I != EI; ++I) {
2288 // Successor may be pruned out during CFG construction.
2289 if (!I.getBlock())
2290 continue;
2291
2292 const CaseStmt *Case = I.getCase();
2293
2294 // Evaluate the LHS of the case value.
2295 llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
2296 assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
2297
2298 // Get the RHS of the case, if it exists.
2299 llvm::APSInt V2;
2300 if (const Expr *E = Case->getRHS())
2301 V2 = E->EvaluateKnownConstInt(getContext());
2302 else
2303 V2 = V1;
2304
2305 ProgramStateRef StateCase;
2306 if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
2307 std::tie(StateCase, DefaultSt) =
2308 DefaultSt->assumeInclusiveRange(*NL, V1, V2);
2309 else // UnknownVal
2310 StateCase = DefaultSt;
2311
2312 if (StateCase)
2313 builder.generateCaseStmtNode(I, StateCase);
2314
2315 // Now "assume" that the case doesn't match. Add this state
2316 // to the default state (if it is feasible).
2317 if (DefaultSt)
2318 defaultIsFeasible = true;
2319 else {
2320 defaultIsFeasible = false;
2321 break;
2322 }
2323 }
2324
2325 if (!defaultIsFeasible)
2326 return;
2327
2328 // If we have switch(enum value), the default branch is not
2329 // feasible if all of the enum constants not covered by 'case:' statements
2330 // are not feasible values for the switch condition.
2331 //
2332 // Note that this isn't as accurate as it could be. Even if there isn't
2333 // a case for a particular enum value as long as that enum value isn't
2334 // feasible then it shouldn't be considered for making 'default:' reachable.
2335 const SwitchStmt *SS = builder.getSwitch();
2336 const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
2337 if (CondExpr->getType()->getAs<EnumType>()) {
2338 if (SS->isAllEnumCasesCovered())
2339 return;
2340 }
2341
2342 builder.generateDefaultCaseNode(DefaultSt);
2343 }
2344
2345 //===----------------------------------------------------------------------===//
2346 // Transfer functions: Loads and stores.
2347 //===----------------------------------------------------------------------===//
2348
VisitCommonDeclRefExpr(const Expr * Ex,const NamedDecl * D,ExplodedNode * Pred,ExplodedNodeSet & Dst)2349 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
2350 ExplodedNode *Pred,
2351 ExplodedNodeSet &Dst) {
2352 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2353
2354 ProgramStateRef state = Pred->getState();
2355 const LocationContext *LCtx = Pred->getLocationContext();
2356
2357 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2358 // C permits "extern void v", and if you cast the address to a valid type,
2359 // you can even do things with it. We simply pretend
2360 assert(Ex->isGLValue() || VD->getType()->isVoidType());
2361 const LocationContext *LocCtxt = Pred->getLocationContext();
2362 const Decl *D = LocCtxt->getDecl();
2363 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
2364 const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
2365 Optional<std::pair<SVal, QualType>> VInfo;
2366
2367 if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
2368 DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
2369 MD->getParent()->isLambda()) {
2370 // Lookup the field of the lambda.
2371 const CXXRecordDecl *CXXRec = MD->getParent();
2372 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
2373 FieldDecl *LambdaThisCaptureField;
2374 CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
2375
2376 // Sema follows a sequence of complex rules to determine whether the
2377 // variable should be captured.
2378 if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
2379 Loc CXXThis =
2380 svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame());
2381 SVal CXXThisVal = state->getSVal(CXXThis);
2382 VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
2383 }
2384 }
2385
2386 if (!VInfo)
2387 VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
2388
2389 SVal V = VInfo->first;
2390 bool IsReference = VInfo->second->isReferenceType();
2391
2392 // For references, the 'lvalue' is the pointer address stored in the
2393 // reference region.
2394 if (IsReference) {
2395 if (const MemRegion *R = V.getAsRegion())
2396 V = state->getSVal(R);
2397 else
2398 V = UnknownVal();
2399 }
2400
2401 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2402 ProgramPoint::PostLValueKind);
2403 return;
2404 }
2405 if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
2406 assert(!Ex->isGLValue());
2407 SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2408 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2409 return;
2410 }
2411 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2412 SVal V = svalBuilder.getFunctionPointer(FD);
2413 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2414 ProgramPoint::PostLValueKind);
2415 return;
2416 }
2417 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
2418 // FIXME: Compute lvalue of field pointers-to-member.
2419 // Right now we just use a non-null void pointer, so that it gives proper
2420 // results in boolean contexts.
2421 // FIXME: Maybe delegate this to the surrounding operator&.
2422 // Note how this expression is lvalue, however pointer-to-member is NonLoc.
2423 SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2424 currBldrCtx->blockCount());
2425 state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2426 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2427 ProgramPoint::PostLValueKind);
2428 return;
2429 }
2430 if (isa<BindingDecl>(D)) {
2431 // FIXME: proper support for bound declarations.
2432 // For now, let's just prevent crashing.
2433 return;
2434 }
2435
2436 llvm_unreachable("Support for this Decl not implemented.");
2437 }
2438
2439 /// VisitArraySubscriptExpr - Transfer function for array accesses
VisitArraySubscriptExpr(const ArraySubscriptExpr * A,ExplodedNode * Pred,ExplodedNodeSet & Dst)2440 void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
2441 ExplodedNode *Pred,
2442 ExplodedNodeSet &Dst){
2443 const Expr *Base = A->getBase()->IgnoreParens();
2444 const Expr *Idx = A->getIdx()->IgnoreParens();
2445
2446 ExplodedNodeSet CheckerPreStmt;
2447 getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2448
2449 ExplodedNodeSet EvalSet;
2450 StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2451
2452 bool IsVectorType = A->getBase()->getType()->isVectorType();
2453
2454 // The "like" case is for situations where C standard prohibits the type to
2455 // be an lvalue, e.g. taking the address of a subscript of an expression of
2456 // type "void *".
2457 bool IsGLValueLike = A->isGLValue() ||
2458 (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
2459
2460 for (auto *Node : CheckerPreStmt) {
2461 const LocationContext *LCtx = Node->getLocationContext();
2462 ProgramStateRef state = Node->getState();
2463
2464 if (IsGLValueLike) {
2465 QualType T = A->getType();
2466
2467 // One of the forbidden LValue types! We still need to have sensible
2468 // symbolic locations to represent this stuff. Note that arithmetic on
2469 // void pointers is a GCC extension.
2470 if (T->isVoidType())
2471 T = getContext().CharTy;
2472
2473 SVal V = state->getLValue(T,
2474 state->getSVal(Idx, LCtx),
2475 state->getSVal(Base, LCtx));
2476 Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2477 ProgramPoint::PostLValueKind);
2478 } else if (IsVectorType) {
2479 // FIXME: non-glvalue vector reads are not modelled.
2480 Bldr.generateNode(A, Node, state, nullptr);
2481 } else {
2482 llvm_unreachable("Array subscript should be an lValue when not \
2483 a vector and not a forbidden lvalue type");
2484 }
2485 }
2486
2487 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2488 }
2489
2490 /// VisitMemberExpr - Transfer function for member expressions.
VisitMemberExpr(const MemberExpr * M,ExplodedNode * Pred,ExplodedNodeSet & Dst)2491 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
2492 ExplodedNodeSet &Dst) {
2493 // FIXME: Prechecks eventually go in ::Visit().
2494 ExplodedNodeSet CheckedSet;
2495 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2496
2497 ExplodedNodeSet EvalSet;
2498 ValueDecl *Member = M->getMemberDecl();
2499
2500 // Handle static member variables and enum constants accessed via
2501 // member syntax.
2502 if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2503 for (const auto I : CheckedSet)
2504 VisitCommonDeclRefExpr(M, Member, I, EvalSet);
2505 } else {
2506 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2507 ExplodedNodeSet Tmp;
2508
2509 for (const auto I : CheckedSet) {
2510 ProgramStateRef state = I->getState();
2511 const LocationContext *LCtx = I->getLocationContext();
2512 Expr *BaseExpr = M->getBase();
2513
2514 // Handle C++ method calls.
2515 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
2516 if (MD->isInstance())
2517 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2518
2519 SVal MDVal = svalBuilder.getFunctionPointer(MD);
2520 state = state->BindExpr(M, LCtx, MDVal);
2521
2522 Bldr.generateNode(M, I, state);
2523 continue;
2524 }
2525
2526 // Handle regular struct fields / member variables.
2527 state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2528 SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
2529
2530 const auto *field = cast<FieldDecl>(Member);
2531 SVal L = state->getLValue(field, baseExprVal);
2532
2533 if (M->isGLValue() || M->getType()->isArrayType()) {
2534 // We special-case rvalues of array type because the analyzer cannot
2535 // reason about them, since we expect all regions to be wrapped in Locs.
2536 // We instead treat these as lvalues and assume that they will decay to
2537 // pointers as soon as they are used.
2538 if (!M->isGLValue()) {
2539 assert(M->getType()->isArrayType());
2540 const auto *PE =
2541 dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
2542 if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2543 llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2544 }
2545 }
2546
2547 if (field->getType()->isReferenceType()) {
2548 if (const MemRegion *R = L.getAsRegion())
2549 L = state->getSVal(R);
2550 else
2551 L = UnknownVal();
2552 }
2553
2554 Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
2555 ProgramPoint::PostLValueKind);
2556 } else {
2557 Bldr.takeNodes(I);
2558 evalLoad(Tmp, M, M, I, state, L);
2559 Bldr.addNodes(Tmp);
2560 }
2561 }
2562 }
2563
2564 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2565 }
2566
VisitAtomicExpr(const AtomicExpr * AE,ExplodedNode * Pred,ExplodedNodeSet & Dst)2567 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
2568 ExplodedNodeSet &Dst) {
2569 ExplodedNodeSet AfterPreSet;
2570 getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2571
2572 // For now, treat all the arguments to C11 atomics as escaping.
2573 // FIXME: Ideally we should model the behavior of the atomics precisely here.
2574
2575 ExplodedNodeSet AfterInvalidateSet;
2576 StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2577
2578 for (const auto I : AfterPreSet) {
2579 ProgramStateRef State = I->getState();
2580 const LocationContext *LCtx = I->getLocationContext();
2581
2582 SmallVector<SVal, 8> ValuesToInvalidate;
2583 for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2584 const Expr *SubExpr = AE->getSubExprs()[SI];
2585 SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2586 ValuesToInvalidate.push_back(SubExprVal);
2587 }
2588
2589 State = State->invalidateRegions(ValuesToInvalidate, AE,
2590 currBldrCtx->blockCount(),
2591 LCtx,
2592 /*CausedByPointerEscape*/true,
2593 /*Symbols=*/nullptr);
2594
2595 SVal ResultVal = UnknownVal();
2596 State = State->BindExpr(AE, LCtx, ResultVal);
2597 Bldr.generateNode(AE, I, State, nullptr,
2598 ProgramPoint::PostStmtKind);
2599 }
2600
2601 getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2602 }
2603
2604 // A value escapes in three possible cases:
2605 // (1) We are binding to something that is not a memory region.
2606 // (2) We are binding to a MemrRegion that does not have stack storage.
2607 // (3) We are binding to a MemRegion with stack storage that the store
2608 // does not understand.
processPointerEscapedOnBind(ProgramStateRef State,SVal Loc,SVal Val,const LocationContext * LCtx)2609 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2610 SVal Loc,
2611 SVal Val,
2612 const LocationContext *LCtx) {
2613 // Are we storing to something that causes the value to "escape"?
2614 bool escapes = true;
2615
2616 // TODO: Move to StoreManager.
2617 if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2618 escapes = !regionLoc->getRegion()->hasStackStorage();
2619
2620 if (!escapes) {
2621 // To test (3), generate a new state with the binding added. If it is
2622 // the same state, then it escapes (since the store cannot represent
2623 // the binding).
2624 // Do this only if we know that the store is not supposed to generate the
2625 // same state.
2626 SVal StoredVal = State->getSVal(regionLoc->getRegion());
2627 if (StoredVal != Val)
2628 escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
2629 }
2630 }
2631
2632 // If our store can represent the binding and we aren't storing to something
2633 // that doesn't have local storage then just return and have the simulation
2634 // state continue as is.
2635 if (!escapes)
2636 return State;
2637
2638 // Otherwise, find all symbols referenced by 'val' that we are tracking
2639 // and stop tracking them.
2640 State = escapeValue(State, Val, PSK_EscapeOnBind);
2641 return State;
2642 }
2643
2644 ProgramStateRef
notifyCheckersOfPointerEscape(ProgramStateRef State,const InvalidatedSymbols * Invalidated,ArrayRef<const MemRegion * > ExplicitRegions,ArrayRef<const MemRegion * > Regions,const CallEvent * Call,RegionAndSymbolInvalidationTraits & ITraits)2645 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2646 const InvalidatedSymbols *Invalidated,
2647 ArrayRef<const MemRegion *> ExplicitRegions,
2648 ArrayRef<const MemRegion *> Regions,
2649 const CallEvent *Call,
2650 RegionAndSymbolInvalidationTraits &ITraits) {
2651 if (!Invalidated || Invalidated->empty())
2652 return State;
2653
2654 if (!Call)
2655 return getCheckerManager().runCheckersForPointerEscape(State,
2656 *Invalidated,
2657 nullptr,
2658 PSK_EscapeOther,
2659 &ITraits);
2660
2661 // If the symbols were invalidated by a call, we want to find out which ones
2662 // were invalidated directly due to being arguments to the call.
2663 InvalidatedSymbols SymbolsDirectlyInvalidated;
2664 for (const auto I : ExplicitRegions) {
2665 if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
2666 SymbolsDirectlyInvalidated.insert(R->getSymbol());
2667 }
2668
2669 InvalidatedSymbols SymbolsIndirectlyInvalidated;
2670 for (const auto &sym : *Invalidated) {
2671 if (SymbolsDirectlyInvalidated.count(sym))
2672 continue;
2673 SymbolsIndirectlyInvalidated.insert(sym);
2674 }
2675
2676 if (!SymbolsDirectlyInvalidated.empty())
2677 State = getCheckerManager().runCheckersForPointerEscape(State,
2678 SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2679
2680 // Notify about the symbols that get indirectly invalidated by the call.
2681 if (!SymbolsIndirectlyInvalidated.empty())
2682 State = getCheckerManager().runCheckersForPointerEscape(State,
2683 SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2684
2685 return State;
2686 }
2687
2688 /// evalBind - Handle the semantics of binding a value to a specific location.
2689 /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
evalBind(ExplodedNodeSet & Dst,const Stmt * StoreE,ExplodedNode * Pred,SVal location,SVal Val,bool atDeclInit,const ProgramPoint * PP)2690 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2691 ExplodedNode *Pred,
2692 SVal location, SVal Val,
2693 bool atDeclInit, const ProgramPoint *PP) {
2694 const LocationContext *LC = Pred->getLocationContext();
2695 PostStmt PS(StoreE, LC);
2696 if (!PP)
2697 PP = &PS;
2698
2699 // Do a previsit of the bind.
2700 ExplodedNodeSet CheckedSet;
2701 getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2702 StoreE, *this, *PP);
2703
2704 StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2705
2706 // If the location is not a 'Loc', it will already be handled by
2707 // the checkers. There is nothing left to do.
2708 if (!location.getAs<Loc>()) {
2709 const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2710 /*tag*/nullptr);
2711 ProgramStateRef state = Pred->getState();
2712 state = processPointerEscapedOnBind(state, location, Val, LC);
2713 Bldr.generateNode(L, state, Pred);
2714 return;
2715 }
2716
2717 for (const auto PredI : CheckedSet) {
2718 ProgramStateRef state = PredI->getState();
2719
2720 state = processPointerEscapedOnBind(state, location, Val, LC);
2721
2722 // When binding the value, pass on the hint that this is a initialization.
2723 // For initializations, we do not need to inform clients of region
2724 // changes.
2725 state = state->bindLoc(location.castAs<Loc>(),
2726 Val, LC, /* notifyChanges = */ !atDeclInit);
2727
2728 const MemRegion *LocReg = nullptr;
2729 if (Optional<loc::MemRegionVal> LocRegVal =
2730 location.getAs<loc::MemRegionVal>()) {
2731 LocReg = LocRegVal->getRegion();
2732 }
2733
2734 const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2735 Bldr.generateNode(L, state, PredI);
2736 }
2737 }
2738
2739 /// evalStore - Handle the semantics of a store via an assignment.
2740 /// @param Dst The node set to store generated state nodes
2741 /// @param AssignE The assignment expression if the store happens in an
2742 /// assignment.
2743 /// @param LocationE The location expression that is stored to.
2744 /// @param state The current simulation state
2745 /// @param location The location to store the value
2746 /// @param Val The value to be stored
evalStore(ExplodedNodeSet & Dst,const Expr * AssignE,const Expr * LocationE,ExplodedNode * Pred,ProgramStateRef state,SVal location,SVal Val,const ProgramPointTag * tag)2747 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2748 const Expr *LocationE,
2749 ExplodedNode *Pred,
2750 ProgramStateRef state, SVal location, SVal Val,
2751 const ProgramPointTag *tag) {
2752 // Proceed with the store. We use AssignE as the anchor for the PostStore
2753 // ProgramPoint if it is non-NULL, and LocationE otherwise.
2754 const Expr *StoreE = AssignE ? AssignE : LocationE;
2755
2756 // Evaluate the location (checks for bad dereferences).
2757 ExplodedNodeSet Tmp;
2758 evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
2759
2760 if (Tmp.empty())
2761 return;
2762
2763 if (location.isUndef())
2764 return;
2765
2766 for (const auto I : Tmp)
2767 evalBind(Dst, StoreE, I, location, Val, false);
2768 }
2769
evalLoad(ExplodedNodeSet & Dst,const Expr * NodeEx,const Expr * BoundEx,ExplodedNode * Pred,ProgramStateRef state,SVal location,const ProgramPointTag * tag,QualType LoadTy)2770 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2771 const Expr *NodeEx,
2772 const Expr *BoundEx,
2773 ExplodedNode *Pred,
2774 ProgramStateRef state,
2775 SVal location,
2776 const ProgramPointTag *tag,
2777 QualType LoadTy) {
2778 assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2779 assert(NodeEx);
2780 assert(BoundEx);
2781 // Evaluate the location (checks for bad dereferences).
2782 ExplodedNodeSet Tmp;
2783 evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
2784 if (Tmp.empty())
2785 return;
2786
2787 StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2788 if (location.isUndef())
2789 return;
2790
2791 // Proceed with the load.
2792 for (const auto I : Tmp) {
2793 state = I->getState();
2794 const LocationContext *LCtx = I->getLocationContext();
2795
2796 SVal V = UnknownVal();
2797 if (location.isValid()) {
2798 if (LoadTy.isNull())
2799 LoadTy = BoundEx->getType();
2800 V = state->getSVal(location.castAs<Loc>(), LoadTy);
2801 }
2802
2803 Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
2804 ProgramPoint::PostLoadKind);
2805 }
2806 }
2807
evalLocation(ExplodedNodeSet & Dst,const Stmt * NodeEx,const Stmt * BoundEx,ExplodedNode * Pred,ProgramStateRef state,SVal location,const ProgramPointTag * tag,bool isLoad)2808 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2809 const Stmt *NodeEx,
2810 const Stmt *BoundEx,
2811 ExplodedNode *Pred,
2812 ProgramStateRef state,
2813 SVal location,
2814 const ProgramPointTag *tag,
2815 bool isLoad) {
2816 StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2817 // Early checks for performance reason.
2818 if (location.isUnknown()) {
2819 return;
2820 }
2821
2822 ExplodedNodeSet Src;
2823 BldrTop.takeNodes(Pred);
2824 StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2825 if (Pred->getState() != state) {
2826 // Associate this new state with an ExplodedNode.
2827 // FIXME: If I pass null tag, the graph is incorrect, e.g for
2828 // int *p;
2829 // p = 0;
2830 // *p = 0xDEADBEEF;
2831 // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2832 // instead "int *p" is noted as
2833 // "Variable 'p' initialized to a null pointer value"
2834
2835 static SimpleProgramPointTag tag(TagProviderName, "Location");
2836 Bldr.generateNode(NodeEx, Pred, state, &tag);
2837 }
2838 ExplodedNodeSet Tmp;
2839 getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2840 NodeEx, BoundEx, *this);
2841 BldrTop.addNodes(Tmp);
2842 }
2843
2844 std::pair<const ProgramPointTag *, const ProgramPointTag*>
geteagerlyAssumeBinOpBifurcationTags()2845 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2846 static SimpleProgramPointTag
2847 eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2848 "Eagerly Assume True"),
2849 eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2850 "Eagerly Assume False");
2851 return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2852 &eagerlyAssumeBinOpBifurcationFalse);
2853 }
2854
evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet & Dst,ExplodedNodeSet & Src,const Expr * Ex)2855 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2856 ExplodedNodeSet &Src,
2857 const Expr *Ex) {
2858 StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2859
2860 for (const auto Pred : Src) {
2861 // Test if the previous node was as the same expression. This can happen
2862 // when the expression fails to evaluate to anything meaningful and
2863 // (as an optimization) we don't generate a node.
2864 ProgramPoint P = Pred->getLocation();
2865 if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2866 continue;
2867 }
2868
2869 ProgramStateRef state = Pred->getState();
2870 SVal V = state->getSVal(Ex, Pred->getLocationContext());
2871 Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2872 if (SEV && SEV->isExpression()) {
2873 const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2874 geteagerlyAssumeBinOpBifurcationTags();
2875
2876 ProgramStateRef StateTrue, StateFalse;
2877 std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2878
2879 // First assume that the condition is true.
2880 if (StateTrue) {
2881 SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2882 StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2883 Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2884 }
2885
2886 // Next, assume that the condition is false.
2887 if (StateFalse) {
2888 SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2889 StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2890 Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2891 }
2892 }
2893 }
2894 }
2895
VisitGCCAsmStmt(const GCCAsmStmt * A,ExplodedNode * Pred,ExplodedNodeSet & Dst)2896 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2897 ExplodedNodeSet &Dst) {
2898 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2899 // We have processed both the inputs and the outputs. All of the outputs
2900 // should evaluate to Locs. Nuke all of their values.
2901
2902 // FIXME: Some day in the future it would be nice to allow a "plug-in"
2903 // which interprets the inline asm and stores proper results in the
2904 // outputs.
2905
2906 ProgramStateRef state = Pred->getState();
2907
2908 for (const Expr *O : A->outputs()) {
2909 SVal X = state->getSVal(O, Pred->getLocationContext());
2910 assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
2911
2912 if (Optional<Loc> LV = X.getAs<Loc>())
2913 state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2914 }
2915
2916 Bldr.generateNode(A, Pred, state);
2917 }
2918
VisitMSAsmStmt(const MSAsmStmt * A,ExplodedNode * Pred,ExplodedNodeSet & Dst)2919 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2920 ExplodedNodeSet &Dst) {
2921 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2922 Bldr.generateNode(A, Pred, Pred->getState());
2923 }
2924
2925 //===----------------------------------------------------------------------===//
2926 // Visualization.
2927 //===----------------------------------------------------------------------===//
2928
2929 #ifndef NDEBUG
2930 static ExprEngine* GraphPrintCheckerState;
2931 static SourceManager* GraphPrintSourceManager;
2932
2933 namespace llvm {
2934
2935 template<>
2936 struct DOTGraphTraits<ExplodedNode*> : public DefaultDOTGraphTraits {
DOTGraphTraitsllvm::DOTGraphTraits2937 DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2938
2939 // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
2940 // work.
getNodeAttributesllvm::DOTGraphTraits2941 static std::string getNodeAttributes(const ExplodedNode *N, void*) {
2942 return {};
2943 }
2944
2945 // De-duplicate some source location pretty-printing.
printLocationllvm::DOTGraphTraits2946 static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
2947 if (SLoc.isFileID()) {
2948 Out << "\\lline="
2949 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
2950 << " col="
2951 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
2952 << "\\l";
2953 }
2954 }
2955
getNodeLabelllvm::DOTGraphTraits2956 static std::string getNodeLabel(const ExplodedNode *N, void*){
2957 std::string sbuf;
2958 llvm::raw_string_ostream Out(sbuf);
2959
2960 // Program Location.
2961 ProgramPoint Loc = N->getLocation();
2962
2963 switch (Loc.getKind()) {
2964 case ProgramPoint::BlockEntranceKind:
2965 Out << "Block Entrance: B"
2966 << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
2967 break;
2968
2969 case ProgramPoint::BlockExitKind:
2970 assert(false);
2971 break;
2972
2973 case ProgramPoint::CallEnterKind:
2974 Out << "CallEnter";
2975 break;
2976
2977 case ProgramPoint::CallExitBeginKind:
2978 Out << "CallExitBegin";
2979 break;
2980
2981 case ProgramPoint::CallExitEndKind:
2982 Out << "CallExitEnd";
2983 break;
2984
2985 case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
2986 Out << "PostStmtPurgeDeadSymbols";
2987 break;
2988
2989 case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
2990 Out << "PreStmtPurgeDeadSymbols";
2991 break;
2992
2993 case ProgramPoint::EpsilonKind:
2994 Out << "Epsilon Point";
2995 break;
2996
2997 case ProgramPoint::LoopExitKind: {
2998 LoopExit LE = Loc.castAs<LoopExit>();
2999 Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
3000 break;
3001 }
3002
3003 case ProgramPoint::PreImplicitCallKind: {
3004 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
3005 Out << "PreCall: ";
3006
3007 // FIXME: Get proper printing options.
3008 PC.getDecl()->print(Out, LangOptions());
3009 printLocation(Out, PC.getLocation());
3010 break;
3011 }
3012
3013 case ProgramPoint::PostImplicitCallKind: {
3014 ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
3015 Out << "PostCall: ";
3016
3017 // FIXME: Get proper printing options.
3018 PC.getDecl()->print(Out, LangOptions());
3019 printLocation(Out, PC.getLocation());
3020 break;
3021 }
3022
3023 case ProgramPoint::PostInitializerKind: {
3024 Out << "PostInitializer: ";
3025 const CXXCtorInitializer *Init =
3026 Loc.castAs<PostInitializer>().getInitializer();
3027 if (const FieldDecl *FD = Init->getAnyMember())
3028 Out << *FD;
3029 else {
3030 QualType Ty = Init->getTypeSourceInfo()->getType();
3031 Ty = Ty.getLocalUnqualifiedType();
3032 LangOptions LO; // FIXME.
3033 Ty.print(Out, LO);
3034 }
3035 break;
3036 }
3037
3038 case ProgramPoint::BlockEdgeKind: {
3039 const BlockEdge &E = Loc.castAs<BlockEdge>();
3040 Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
3041 << E.getDst()->getBlockID() << ')';
3042
3043 if (const Stmt *T = E.getSrc()->getTerminator()) {
3044 SourceLocation SLoc = T->getLocStart();
3045
3046 Out << "\\|Terminator: ";
3047 LangOptions LO; // FIXME.
3048 E.getSrc()->printTerminator(Out, LO);
3049
3050 if (SLoc.isFileID()) {
3051 Out << "\\lline="
3052 << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
3053 << " col="
3054 << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
3055 }
3056
3057 if (isa<SwitchStmt>(T)) {
3058 const Stmt *Label = E.getDst()->getLabel();
3059
3060 if (Label) {
3061 if (const auto *C = dyn_cast<CaseStmt>(Label)) {
3062 Out << "\\lcase ";
3063 LangOptions LO; // FIXME.
3064 if (C->getLHS())
3065 C->getLHS()->printPretty(Out, nullptr, PrintingPolicy(LO));
3066
3067 if (const Stmt *RHS = C->getRHS()) {
3068 Out << " .. ";
3069 RHS->printPretty(Out, nullptr, PrintingPolicy(LO));
3070 }
3071
3072 Out << ":";
3073 }
3074 else {
3075 assert(isa<DefaultStmt>(Label));
3076 Out << "\\ldefault:";
3077 }
3078 }
3079 else
3080 Out << "\\l(implicit) default:";
3081 }
3082 else if (isa<IndirectGotoStmt>(T)) {
3083 // FIXME
3084 }
3085 else {
3086 Out << "\\lCondition: ";
3087 if (*E.getSrc()->succ_begin() == E.getDst())
3088 Out << "true";
3089 else
3090 Out << "false";
3091 }
3092
3093 Out << "\\l";
3094 }
3095
3096 break;
3097 }
3098
3099 default: {
3100 const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
3101 assert(S != nullptr && "Expecting non-null Stmt");
3102
3103 Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
3104 LangOptions LO; // FIXME.
3105 S->printPretty(Out, nullptr, PrintingPolicy(LO));
3106 printLocation(Out, S->getLocStart());
3107
3108 if (Loc.getAs<PreStmt>())
3109 Out << "\\lPreStmt\\l;";
3110 else if (Loc.getAs<PostLoad>())
3111 Out << "\\lPostLoad\\l;";
3112 else if (Loc.getAs<PostStore>())
3113 Out << "\\lPostStore\\l";
3114 else if (Loc.getAs<PostLValue>())
3115 Out << "\\lPostLValue\\l";
3116 else if (Loc.getAs<PostAllocatorCall>())
3117 Out << "\\lPostAllocatorCall\\l";
3118
3119 break;
3120 }
3121 }
3122
3123 ProgramStateRef state = N->getState();
3124 Out << "\\|StateID: " << (const void*) state.get()
3125 << " NodeID: " << (const void*) N << "\\|";
3126
3127 state->printDOT(Out, N->getLocationContext());
3128
3129 Out << "\\l";
3130
3131 if (const ProgramPointTag *tag = Loc.getTag()) {
3132 Out << "\\|Tag: " << tag->getTagDescription();
3133 Out << "\\l";
3134 }
3135 return Out.str();
3136 }
3137 };
3138
3139 } // namespace llvm
3140 #endif
3141
ViewGraph(bool trim)3142 void ExprEngine::ViewGraph(bool trim) {
3143 #ifndef NDEBUG
3144 if (trim) {
3145 std::vector<const ExplodedNode *> Src;
3146
3147 // Flush any outstanding reports to make sure we cover all the nodes.
3148 // This does not cause them to get displayed.
3149 for (const auto I : BR)
3150 const_cast<BugType *>(I)->FlushReports(BR);
3151
3152 // Iterate through the reports and get their nodes.
3153 for (BugReporter::EQClasses_iterator
3154 EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3155 const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
3156 if (N) Src.push_back(N);
3157 }
3158
3159 ViewGraph(Src);
3160 }
3161 else {
3162 GraphPrintCheckerState = this;
3163 GraphPrintSourceManager = &getContext().getSourceManager();
3164
3165 llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
3166
3167 GraphPrintCheckerState = nullptr;
3168 GraphPrintSourceManager = nullptr;
3169 }
3170 #endif
3171 }
3172
ViewGraph(ArrayRef<const ExplodedNode * > Nodes)3173 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
3174 #ifndef NDEBUG
3175 GraphPrintCheckerState = this;
3176 GraphPrintSourceManager = &getContext().getSourceManager();
3177
3178 std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
3179
3180 if (!TrimmedG.get())
3181 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3182 else
3183 llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
3184
3185 GraphPrintCheckerState = nullptr;
3186 GraphPrintSourceManager = nullptr;
3187 #endif
3188 }
3189