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