1 //=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines ExprEngine's support for C expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ExprCXX.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
18 
19 using namespace clang;
20 using namespace ento;
21 using llvm::APSInt;
22 
23 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
24                                      ExplodedNode *Pred,
25                                      ExplodedNodeSet &Dst) {
26 
27   Expr *LHS = B->getLHS()->IgnoreParens();
28   Expr *RHS = B->getRHS()->IgnoreParens();
29 
30   // FIXME: Prechecks eventually go in ::Visit().
31   ExplodedNodeSet CheckedSet;
32   ExplodedNodeSet Tmp2;
33   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
34 
35   // With both the LHS and RHS evaluated, process the operation itself.
36   for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
37          it != ei; ++it) {
38 
39     ProgramStateRef state = (*it)->getState();
40     const LocationContext *LCtx = (*it)->getLocationContext();
41     SVal LeftV = state->getSVal(LHS, LCtx);
42     SVal RightV = state->getSVal(RHS, LCtx);
43 
44     BinaryOperator::Opcode Op = B->getOpcode();
45 
46     if (Op == BO_Assign) {
47       // EXPERIMENTAL: "Conjured" symbols.
48       // FIXME: Handle structs.
49       if (RightV.isUnknown()) {
50         unsigned Count = currBldrCtx->blockCount();
51         RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
52                                               Count);
53       }
54       // Simulate the effects of a "store":  bind the value of the RHS
55       // to the L-Value represented by the LHS.
56       SVal ExprVal = B->isGLValue() ? LeftV : RightV;
57       evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
58                 LeftV, RightV);
59       continue;
60     }
61 
62     if (!B->isAssignmentOp()) {
63       StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
64 
65       if (B->isAdditiveOp()) {
66         // If one of the operands is a location, conjure a symbol for the other
67         // one (offset) if it's unknown so that memory arithmetic always
68         // results in an ElementRegion.
69         // TODO: This can be removed after we enable history tracking with
70         // SymSymExpr.
71         unsigned Count = currBldrCtx->blockCount();
72         if (LeftV.getAs<Loc>() &&
73             RHS->getType()->isIntegralOrEnumerationType() &&
74             RightV.isUnknown()) {
75           RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(),
76                                                 Count);
77         }
78         if (RightV.getAs<Loc>() &&
79             LHS->getType()->isIntegralOrEnumerationType() &&
80             LeftV.isUnknown()) {
81           LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(),
82                                                Count);
83         }
84       }
85 
86       // Although we don't yet model pointers-to-members, we do need to make
87       // sure that the members of temporaries have a valid 'this' pointer for
88       // other checks.
89       if (B->getOpcode() == BO_PtrMemD)
90         state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
91 
92       // Process non-assignments except commas or short-circuited
93       // logical expressions (LAnd and LOr).
94       SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
95       if (Result.isUnknown()) {
96         Bldr.generateNode(B, *it, state);
97         continue;
98       }
99 
100       state = state->BindExpr(B, LCtx, Result);
101       Bldr.generateNode(B, *it, state);
102       continue;
103     }
104 
105     assert (B->isCompoundAssignmentOp());
106 
107     switch (Op) {
108       default:
109         llvm_unreachable("Invalid opcode for compound assignment.");
110       case BO_MulAssign: Op = BO_Mul; break;
111       case BO_DivAssign: Op = BO_Div; break;
112       case BO_RemAssign: Op = BO_Rem; break;
113       case BO_AddAssign: Op = BO_Add; break;
114       case BO_SubAssign: Op = BO_Sub; break;
115       case BO_ShlAssign: Op = BO_Shl; break;
116       case BO_ShrAssign: Op = BO_Shr; break;
117       case BO_AndAssign: Op = BO_And; break;
118       case BO_XorAssign: Op = BO_Xor; break;
119       case BO_OrAssign:  Op = BO_Or;  break;
120     }
121 
122     // Perform a load (the LHS).  This performs the checks for
123     // null dereferences, and so on.
124     ExplodedNodeSet Tmp;
125     SVal location = LeftV;
126     evalLoad(Tmp, B, LHS, *it, state, location);
127 
128     for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
129          ++I) {
130 
131       state = (*I)->getState();
132       const LocationContext *LCtx = (*I)->getLocationContext();
133       SVal V = state->getSVal(LHS, LCtx);
134 
135       // Get the computation type.
136       QualType CTy =
137         cast<CompoundAssignOperator>(B)->getComputationResultType();
138       CTy = getContext().getCanonicalType(CTy);
139 
140       QualType CLHSTy =
141         cast<CompoundAssignOperator>(B)->getComputationLHSType();
142       CLHSTy = getContext().getCanonicalType(CLHSTy);
143 
144       QualType LTy = getContext().getCanonicalType(LHS->getType());
145 
146       // Promote LHS.
147       V = svalBuilder.evalCast(V, CLHSTy, LTy);
148 
149       // Compute the result of the operation.
150       SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
151                                          B->getType(), CTy);
152 
153       // EXPERIMENTAL: "Conjured" symbols.
154       // FIXME: Handle structs.
155 
156       SVal LHSVal;
157 
158       if (Result.isUnknown()) {
159         // The symbolic value is actually for the type of the left-hand side
160         // expression, not the computation type, as this is the value the
161         // LValue on the LHS will bind to.
162         LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
163                                               currBldrCtx->blockCount());
164         // However, we need to convert the symbol to the computation type.
165         Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
166       }
167       else {
168         // The left-hand side may bind to a different value then the
169         // computation type.
170         LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
171       }
172 
173       // In C++, assignment and compound assignment operators return an
174       // lvalue.
175       if (B->isGLValue())
176         state = state->BindExpr(B, LCtx, location);
177       else
178         state = state->BindExpr(B, LCtx, Result);
179 
180       evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
181     }
182   }
183 
184   // FIXME: postvisits eventually go in ::Visit()
185   getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
186 }
187 
188 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
189                                 ExplodedNodeSet &Dst) {
190 
191   CanQualType T = getContext().getCanonicalType(BE->getType());
192 
193   const BlockDecl *BD = BE->getBlockDecl();
194   // Get the value of the block itself.
195   SVal V = svalBuilder.getBlockPointer(BD, T,
196                                        Pred->getLocationContext(),
197                                        currBldrCtx->blockCount());
198 
199   ProgramStateRef State = Pred->getState();
200 
201   // If we created a new MemRegion for the block, we should explicitly bind
202   // the captured variables.
203   if (const BlockDataRegion *BDR =
204       dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
205 
206     BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
207                                               E = BDR->referenced_vars_end();
208 
209     auto CI = BD->capture_begin();
210     auto CE = BD->capture_end();
211     for (; I != E; ++I) {
212       const VarRegion *capturedR = I.getCapturedRegion();
213       const VarRegion *originalR = I.getOriginalRegion();
214 
215       // If the capture had a copy expression, use the result of evaluating
216       // that expression, otherwise use the original value.
217       // We rely on the invariant that the block declaration's capture variables
218       // are a prefix of the BlockDataRegion's referenced vars (which may include
219       // referenced globals, etc.) to enable fast lookup of the capture for a
220       // given referenced var.
221       const Expr *copyExpr = nullptr;
222       if (CI != CE) {
223         assert(CI->getVariable() == capturedR->getDecl());
224         copyExpr = CI->getCopyExpr();
225         CI++;
226       }
227 
228       if (capturedR != originalR) {
229         SVal originalV;
230         if (copyExpr) {
231           originalV = State->getSVal(copyExpr, Pred->getLocationContext());
232         } else {
233           originalV = State->getSVal(loc::MemRegionVal(originalR));
234         }
235         State = State->bindLoc(loc::MemRegionVal(capturedR), originalV);
236       }
237     }
238   }
239 
240   ExplodedNodeSet Tmp;
241   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
242   Bldr.generateNode(BE, Pred,
243                     State->BindExpr(BE, Pred->getLocationContext(), V),
244                     nullptr, ProgramPoint::PostLValueKind);
245 
246   // FIXME: Move all post/pre visits to ::Visit().
247   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
248 }
249 
250 ProgramStateRef ExprEngine::handleLValueBitCast(
251     ProgramStateRef state, const Expr* Ex, const LocationContext* LCtx,
252     QualType T, QualType ExTy, const CastExpr* CastE, StmtNodeBuilder& Bldr,
253     ExplodedNode* Pred) {
254   // Delegate to SValBuilder to process.
255   SVal V = state->getSVal(Ex, LCtx);
256   V = svalBuilder.evalCast(V, T, ExTy);
257   // Negate the result if we're treating the boolean as a signed i1
258   if (CastE->getCastKind() == CK_BooleanToSignedIntegral)
259     V = evalMinus(V);
260   state = state->BindExpr(CastE, LCtx, V);
261   Bldr.generateNode(CastE, Pred, state);
262 
263   return state;
264 }
265 
266 ProgramStateRef ExprEngine::handleLVectorSplat(
267     ProgramStateRef state, const LocationContext* LCtx, const CastExpr* CastE,
268     StmtNodeBuilder &Bldr, ExplodedNode* Pred) {
269   // Recover some path sensitivity by conjuring a new value.
270   QualType resultType = CastE->getType();
271   if (CastE->isGLValue())
272     resultType = getContext().getPointerType(resultType);
273   SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx,
274                                              resultType,
275                                              currBldrCtx->blockCount());
276   state = state->BindExpr(CastE, LCtx, result);
277   Bldr.generateNode(CastE, Pred, state);
278 
279   return state;
280 }
281 
282 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
283                            ExplodedNode *Pred, ExplodedNodeSet &Dst) {
284 
285   ExplodedNodeSet dstPreStmt;
286   getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
287 
288   if (CastE->getCastKind() == CK_LValueToRValue) {
289     for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
290          I!=E; ++I) {
291       ExplodedNode *subExprNode = *I;
292       ProgramStateRef state = subExprNode->getState();
293       const LocationContext *LCtx = subExprNode->getLocationContext();
294       evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
295     }
296     return;
297   }
298 
299   // All other casts.
300   QualType T = CastE->getType();
301   QualType ExTy = Ex->getType();
302 
303   if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
304     T = ExCast->getTypeAsWritten();
305 
306   StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
307   for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
308        I != E; ++I) {
309 
310     Pred = *I;
311     ProgramStateRef state = Pred->getState();
312     const LocationContext *LCtx = Pred->getLocationContext();
313 
314     switch (CastE->getCastKind()) {
315       case CK_LValueToRValue:
316         llvm_unreachable("LValueToRValue casts handled earlier.");
317       case CK_ToVoid:
318         continue;
319         // The analyzer doesn't do anything special with these casts,
320         // since it understands retain/release semantics already.
321       case CK_ARCProduceObject:
322       case CK_ARCConsumeObject:
323       case CK_ARCReclaimReturnedObject:
324       case CK_ARCExtendBlockObject: // Fall-through.
325       case CK_CopyAndAutoreleaseBlockObject:
326         // The analyser can ignore atomic casts for now, although some future
327         // checkers may want to make certain that you're not modifying the same
328         // value through atomic and nonatomic pointers.
329       case CK_AtomicToNonAtomic:
330       case CK_NonAtomicToAtomic:
331         // True no-ops.
332       case CK_NoOp:
333       case CK_ConstructorConversion:
334       case CK_UserDefinedConversion:
335       case CK_FunctionToPointerDecay:
336       case CK_BuiltinFnToFnPtr: {
337         // Copy the SVal of Ex to CastE.
338         ProgramStateRef state = Pred->getState();
339         const LocationContext *LCtx = Pred->getLocationContext();
340         SVal V = state->getSVal(Ex, LCtx);
341         state = state->BindExpr(CastE, LCtx, V);
342         Bldr.generateNode(CastE, Pred, state);
343         continue;
344       }
345       case CK_MemberPointerToBoolean:
346       case CK_PointerToBoolean: {
347         SVal V = state->getSVal(Ex, LCtx);
348         auto PTMSV = V.getAs<nonloc::PointerToMember>();
349         if (PTMSV)
350           V = svalBuilder.makeTruthVal(!PTMSV->isNullMemberPointer(), ExTy);
351         if (V.isUndef() || PTMSV) {
352           state = state->BindExpr(CastE, LCtx, V);
353           Bldr.generateNode(CastE, Pred, state);
354           continue;
355         }
356         // Explicitly proceed with default handler for this case cascade.
357         state =
358             handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
359         continue;
360       }
361       case CK_Dependent:
362       case CK_ArrayToPointerDecay:
363       case CK_BitCast:
364       case CK_AddressSpaceConversion:
365       case CK_BooleanToSignedIntegral:
366       case CK_NullToPointer:
367       case CK_IntegralToPointer:
368       case CK_PointerToIntegral: {
369         SVal V = state->getSVal(Ex, LCtx);
370         if (V.getAs<nonloc::PointerToMember>()) {
371           state = state->BindExpr(CastE, LCtx, UnknownVal());
372           Bldr.generateNode(CastE, Pred, state);
373           continue;
374         }
375         // Explicitly proceed with default handler for this case cascade.
376         state =
377             handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
378         continue;
379       }
380       case CK_IntegralToBoolean:
381       case CK_IntegralToFloating:
382       case CK_FloatingToIntegral:
383       case CK_FloatingToBoolean:
384       case CK_FloatingCast:
385       case CK_FloatingRealToComplex:
386       case CK_FloatingComplexToReal:
387       case CK_FloatingComplexToBoolean:
388       case CK_FloatingComplexCast:
389       case CK_FloatingComplexToIntegralComplex:
390       case CK_IntegralRealToComplex:
391       case CK_IntegralComplexToReal:
392       case CK_IntegralComplexToBoolean:
393       case CK_IntegralComplexCast:
394       case CK_IntegralComplexToFloatingComplex:
395       case CK_CPointerToObjCPointerCast:
396       case CK_BlockPointerToObjCPointerCast:
397       case CK_AnyPointerToBlockPointerCast:
398       case CK_ObjCObjectLValueCast:
399       case CK_ZeroToOCLEvent:
400       case CK_IntToOCLSampler:
401       case CK_LValueBitCast: {
402         state =
403             handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
404         continue;
405       }
406       case CK_IntegralCast: {
407         // Delegate to SValBuilder to process.
408         SVal V = state->getSVal(Ex, LCtx);
409         V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
410         state = state->BindExpr(CastE, LCtx, V);
411         Bldr.generateNode(CastE, Pred, state);
412         continue;
413       }
414       case CK_DerivedToBase:
415       case CK_UncheckedDerivedToBase: {
416         // For DerivedToBase cast, delegate to the store manager.
417         SVal val = state->getSVal(Ex, LCtx);
418         val = getStoreManager().evalDerivedToBase(val, CastE);
419         state = state->BindExpr(CastE, LCtx, val);
420         Bldr.generateNode(CastE, Pred, state);
421         continue;
422       }
423       // Handle C++ dyn_cast.
424       case CK_Dynamic: {
425         SVal val = state->getSVal(Ex, LCtx);
426 
427         // Compute the type of the result.
428         QualType resultType = CastE->getType();
429         if (CastE->isGLValue())
430           resultType = getContext().getPointerType(resultType);
431 
432         bool Failed = false;
433 
434         // Check if the value being cast evaluates to 0.
435         if (val.isZeroConstant())
436           Failed = true;
437         // Else, evaluate the cast.
438         else
439           val = getStoreManager().attemptDownCast(val, T, Failed);
440 
441         if (Failed) {
442           if (T->isReferenceType()) {
443             // A bad_cast exception is thrown if input value is a reference.
444             // Currently, we model this, by generating a sink.
445             Bldr.generateSink(CastE, Pred, state);
446             continue;
447           } else {
448             // If the cast fails on a pointer, bind to 0.
449             state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
450           }
451         } else {
452           // If we don't know if the cast succeeded, conjure a new symbol.
453           if (val.isUnknown()) {
454             DefinedOrUnknownSVal NewSym =
455               svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
456                                            currBldrCtx->blockCount());
457             state = state->BindExpr(CastE, LCtx, NewSym);
458           } else
459             // Else, bind to the derived region value.
460             state = state->BindExpr(CastE, LCtx, val);
461         }
462         Bldr.generateNode(CastE, Pred, state);
463         continue;
464       }
465       case CK_BaseToDerived: {
466         SVal val = state->getSVal(Ex, LCtx);
467         QualType resultType = CastE->getType();
468         if (CastE->isGLValue())
469           resultType = getContext().getPointerType(resultType);
470 
471         bool Failed = false;
472 
473         if (!val.isConstant()) {
474           val = getStoreManager().attemptDownCast(val, T, Failed);
475         }
476 
477         // Failed to cast or the result is unknown, fall back to conservative.
478         if (Failed || val.isUnknown()) {
479           val =
480             svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
481                                          currBldrCtx->blockCount());
482         }
483         state = state->BindExpr(CastE, LCtx, val);
484         Bldr.generateNode(CastE, Pred, state);
485         continue;
486       }
487       case CK_NullToMemberPointer: {
488         SVal V = svalBuilder.getMemberPointer(nullptr);
489         state = state->BindExpr(CastE, LCtx, V);
490         Bldr.generateNode(CastE, Pred, state);
491         continue;
492       }
493       case CK_DerivedToBaseMemberPointer:
494       case CK_BaseToDerivedMemberPointer:
495       case CK_ReinterpretMemberPointer: {
496         SVal V = state->getSVal(Ex, LCtx);
497         if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) {
498           SVal CastedPTMSV = svalBuilder.makePointerToMember(
499               getBasicVals().accumCXXBase(
500                   llvm::make_range<CastExpr::path_const_iterator>(
501                       CastE->path_begin(), CastE->path_end()), *PTMSV));
502           state = state->BindExpr(CastE, LCtx, CastedPTMSV);
503           Bldr.generateNode(CastE, Pred, state);
504           continue;
505         }
506         // Explicitly proceed with default handler for this case cascade.
507         state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
508         continue;
509       }
510       // Various C++ casts that are not handled yet.
511       case CK_ToUnion:
512       case CK_VectorSplat: {
513         state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
514         continue;
515       }
516     }
517   }
518 }
519 
520 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
521                                           ExplodedNode *Pred,
522                                           ExplodedNodeSet &Dst) {
523   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
524 
525   ProgramStateRef State = Pred->getState();
526   const LocationContext *LCtx = Pred->getLocationContext();
527 
528   const Expr *Init = CL->getInitializer();
529   SVal V = State->getSVal(CL->getInitializer(), LCtx);
530 
531   if (isa<CXXConstructExpr>(Init)) {
532     // No work needed. Just pass the value up to this expression.
533   } else {
534     assert(isa<InitListExpr>(Init));
535     Loc CLLoc = State->getLValue(CL, LCtx);
536     State = State->bindLoc(CLLoc, V);
537 
538     if (CL->isGLValue())
539       V = CLLoc;
540   }
541 
542   B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
543 }
544 
545 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
546                                ExplodedNodeSet &Dst) {
547   // Assumption: The CFG has one DeclStmt per Decl.
548   const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
549 
550   if (!VD) {
551     //TODO:AZ: remove explicit insertion after refactoring is done.
552     Dst.insert(Pred);
553     return;
554   }
555 
556   // FIXME: all pre/post visits should eventually be handled by ::Visit().
557   ExplodedNodeSet dstPreVisit;
558   getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
559 
560   ExplodedNodeSet dstEvaluated;
561   StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
562   for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
563        I!=E; ++I) {
564     ExplodedNode *N = *I;
565     ProgramStateRef state = N->getState();
566     const LocationContext *LC = N->getLocationContext();
567 
568     // Decls without InitExpr are not initialized explicitly.
569     if (const Expr *InitEx = VD->getInit()) {
570 
571       // Note in the state that the initialization has occurred.
572       ExplodedNode *UpdatedN = N;
573       SVal InitVal = state->getSVal(InitEx, LC);
574 
575       assert(DS->isSingleDecl());
576       if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
577         assert(InitEx->IgnoreImplicit() == CtorExpr);
578         (void)CtorExpr;
579         // We constructed the object directly in the variable.
580         // No need to bind anything.
581         B.generateNode(DS, UpdatedN, state);
582       } else {
583         // We bound the temp obj region to the CXXConstructExpr. Now recover
584         // the lazy compound value when the variable is not a reference.
585         if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
586             !VD->getType()->isReferenceType()) {
587           if (Optional<loc::MemRegionVal> M =
588                   InitVal.getAs<loc::MemRegionVal>()) {
589             InitVal = state->getSVal(M->getRegion());
590             assert(InitVal.getAs<nonloc::LazyCompoundVal>());
591           }
592         }
593 
594         // Recover some path-sensitivity if a scalar value evaluated to
595         // UnknownVal.
596         if (InitVal.isUnknown()) {
597           QualType Ty = InitEx->getType();
598           if (InitEx->isGLValue()) {
599             Ty = getContext().getPointerType(Ty);
600           }
601 
602           InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
603                                                  currBldrCtx->blockCount());
604         }
605 
606 
607         B.takeNodes(UpdatedN);
608         ExplodedNodeSet Dst2;
609         evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
610         B.addNodes(Dst2);
611       }
612     }
613     else {
614       B.generateNode(DS, N, state);
615     }
616   }
617 
618   getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
619 }
620 
621 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
622                                   ExplodedNodeSet &Dst) {
623   assert(B->getOpcode() == BO_LAnd ||
624          B->getOpcode() == BO_LOr);
625 
626   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
627   ProgramStateRef state = Pred->getState();
628 
629   ExplodedNode *N = Pred;
630   while (!N->getLocation().getAs<BlockEntrance>()) {
631     ProgramPoint P = N->getLocation();
632     assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
633     (void) P;
634     assert(N->pred_size() == 1);
635     N = *N->pred_begin();
636   }
637   assert(N->pred_size() == 1);
638   N = *N->pred_begin();
639   BlockEdge BE = N->getLocation().castAs<BlockEdge>();
640   SVal X;
641 
642   // Determine the value of the expression by introspecting how we
643   // got this location in the CFG.  This requires looking at the previous
644   // block we were in and what kind of control-flow transfer was involved.
645   const CFGBlock *SrcBlock = BE.getSrc();
646   // The only terminator (if there is one) that makes sense is a logical op.
647   CFGTerminator T = SrcBlock->getTerminator();
648   if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
649     (void) Term;
650     assert(Term->isLogicalOp());
651     assert(SrcBlock->succ_size() == 2);
652     // Did we take the true or false branch?
653     unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
654     X = svalBuilder.makeIntVal(constant, B->getType());
655   }
656   else {
657     // If there is no terminator, by construction the last statement
658     // in SrcBlock is the value of the enclosing expression.
659     // However, we still need to constrain that value to be 0 or 1.
660     assert(!SrcBlock->empty());
661     CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
662     const Expr *RHS = cast<Expr>(Elem.getStmt());
663     SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
664 
665     if (RHSVal.isUndef()) {
666       X = RHSVal;
667     } else {
668       DefinedOrUnknownSVal DefinedRHS = RHSVal.castAs<DefinedOrUnknownSVal>();
669       ProgramStateRef StTrue, StFalse;
670       std::tie(StTrue, StFalse) = N->getState()->assume(DefinedRHS);
671       if (StTrue) {
672         if (StFalse) {
673           // We can't constrain the value to 0 or 1.
674           // The best we can do is a cast.
675           X = getSValBuilder().evalCast(RHSVal, B->getType(), RHS->getType());
676         } else {
677           // The value is known to be true.
678           X = getSValBuilder().makeIntVal(1, B->getType());
679         }
680       } else {
681         // The value is known to be false.
682         assert(StFalse && "Infeasible path!");
683         X = getSValBuilder().makeIntVal(0, B->getType());
684       }
685     }
686   }
687   Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
688 }
689 
690 void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
691                                    ExplodedNode *Pred,
692                                    ExplodedNodeSet &Dst) {
693   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
694 
695   ProgramStateRef state = Pred->getState();
696   const LocationContext *LCtx = Pred->getLocationContext();
697   QualType T = getContext().getCanonicalType(IE->getType());
698   unsigned NumInitElements = IE->getNumInits();
699 
700   if (!IE->isGLValue() &&
701       (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
702        T->isAnyComplexType())) {
703     llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
704 
705     // Handle base case where the initializer has no elements.
706     // e.g: static int* myArray[] = {};
707     if (NumInitElements == 0) {
708       SVal V = svalBuilder.makeCompoundVal(T, vals);
709       B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
710       return;
711     }
712 
713     for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
714          ei = IE->rend(); it != ei; ++it) {
715       SVal V = state->getSVal(cast<Expr>(*it), LCtx);
716       vals = getBasicVals().prependSVal(V, vals);
717     }
718 
719     B.generateNode(IE, Pred,
720                    state->BindExpr(IE, LCtx,
721                                    svalBuilder.makeCompoundVal(T, vals)));
722     return;
723   }
724 
725   // Handle scalars: int{5} and int{} and GLvalues.
726   // Note, if the InitListExpr is a GLvalue, it means that there is an address
727   // representing it, so it must have a single init element.
728   assert(NumInitElements <= 1);
729 
730   SVal V;
731   if (NumInitElements == 0)
732     V = getSValBuilder().makeZeroVal(T);
733   else
734     V = state->getSVal(IE->getInit(0), LCtx);
735 
736   B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
737 }
738 
739 void ExprEngine::VisitGuardedExpr(const Expr *Ex,
740                                   const Expr *L,
741                                   const Expr *R,
742                                   ExplodedNode *Pred,
743                                   ExplodedNodeSet &Dst) {
744   assert(L && R);
745 
746   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
747   ProgramStateRef state = Pred->getState();
748   const LocationContext *LCtx = Pred->getLocationContext();
749   const CFGBlock *SrcBlock = nullptr;
750 
751   // Find the predecessor block.
752   ProgramStateRef SrcState = state;
753   for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
754     ProgramPoint PP = N->getLocation();
755     if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
756       assert(N->pred_size() == 1);
757       continue;
758     }
759     SrcBlock = PP.castAs<BlockEdge>().getSrc();
760     SrcState = N->getState();
761     break;
762   }
763 
764   assert(SrcBlock && "missing function entry");
765 
766   // Find the last expression in the predecessor block.  That is the
767   // expression that is used for the value of the ternary expression.
768   bool hasValue = false;
769   SVal V;
770 
771   for (CFGElement CE : llvm::reverse(*SrcBlock)) {
772     if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
773       const Expr *ValEx = cast<Expr>(CS->getStmt());
774       ValEx = ValEx->IgnoreParens();
775 
776       // For GNU extension '?:' operator, the left hand side will be an
777       // OpaqueValueExpr, so get the underlying expression.
778       if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
779         L = OpaqueEx->getSourceExpr();
780 
781       // If the last expression in the predecessor block matches true or false
782       // subexpression, get its the value.
783       if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
784         hasValue = true;
785         V = SrcState->getSVal(ValEx, LCtx);
786       }
787       break;
788     }
789   }
790 
791   if (!hasValue)
792     V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
793                                      currBldrCtx->blockCount());
794 
795   // Generate a new node with the binding from the appropriate path.
796   B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
797 }
798 
799 void ExprEngine::
800 VisitOffsetOfExpr(const OffsetOfExpr *OOE,
801                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
802   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
803   APSInt IV;
804   if (OOE->EvaluateAsInt(IV, getContext())) {
805     assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
806     assert(OOE->getType()->isBuiltinType());
807     assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
808     assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
809     SVal X = svalBuilder.makeIntVal(IV);
810     B.generateNode(OOE, Pred,
811                    Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
812                                               X));
813   }
814   // FIXME: Handle the case where __builtin_offsetof is not a constant.
815 }
816 
817 
818 void ExprEngine::
819 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
820                               ExplodedNode *Pred,
821                               ExplodedNodeSet &Dst) {
822   // FIXME: Prechecks eventually go in ::Visit().
823   ExplodedNodeSet CheckedSet;
824   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
825 
826   ExplodedNodeSet EvalSet;
827   StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
828 
829   QualType T = Ex->getTypeOfArgument();
830 
831   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
832        I != E; ++I) {
833     if (Ex->getKind() == UETT_SizeOf) {
834       if (!T->isIncompleteType() && !T->isConstantSizeType()) {
835         assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
836 
837         // FIXME: Add support for VLA type arguments and VLA expressions.
838         // When that happens, we should probably refactor VLASizeChecker's code.
839         continue;
840       } else if (T->getAs<ObjCObjectType>()) {
841         // Some code tries to take the sizeof an ObjCObjectType, relying that
842         // the compiler has laid out its representation.  Just report Unknown
843         // for these.
844         continue;
845       }
846     }
847 
848     APSInt Value = Ex->EvaluateKnownConstInt(getContext());
849     CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
850 
851     ProgramStateRef state = (*I)->getState();
852     state = state->BindExpr(Ex, (*I)->getLocationContext(),
853                             svalBuilder.makeIntVal(amt.getQuantity(),
854                                                    Ex->getType()));
855     Bldr.generateNode(Ex, *I, state);
856   }
857 
858   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
859 }
860 
861 void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
862                                    const UnaryOperator *U,
863                                    StmtNodeBuilder &Bldr) {
864   // FIXME: We can probably just have some magic in Environment::getSVal()
865   // that propagates values, instead of creating a new node here.
866   //
867   // Unary "+" is a no-op, similar to a parentheses.  We still have places
868   // where it may be a block-level expression, so we need to
869   // generate an extra node that just propagates the value of the
870   // subexpression.
871   const Expr *Ex = U->getSubExpr()->IgnoreParens();
872   ProgramStateRef state = (*I)->getState();
873   const LocationContext *LCtx = (*I)->getLocationContext();
874   Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
875                                            state->getSVal(Ex, LCtx)));
876 }
877 
878 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
879                                     ExplodedNodeSet &Dst) {
880   // FIXME: Prechecks eventually go in ::Visit().
881   ExplodedNodeSet CheckedSet;
882   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
883 
884   ExplodedNodeSet EvalSet;
885   StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
886 
887   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
888        I != E; ++I) {
889     switch (U->getOpcode()) {
890     default: {
891       Bldr.takeNodes(*I);
892       ExplodedNodeSet Tmp;
893       VisitIncrementDecrementOperator(U, *I, Tmp);
894       Bldr.addNodes(Tmp);
895       break;
896     }
897     case UO_Real: {
898       const Expr *Ex = U->getSubExpr()->IgnoreParens();
899 
900       // FIXME: We don't have complex SValues yet.
901       if (Ex->getType()->isAnyComplexType()) {
902         // Just report "Unknown."
903         break;
904       }
905 
906       // For all other types, UO_Real is an identity operation.
907       assert (U->getType() == Ex->getType());
908       ProgramStateRef state = (*I)->getState();
909       const LocationContext *LCtx = (*I)->getLocationContext();
910       Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
911                                                state->getSVal(Ex, LCtx)));
912       break;
913     }
914 
915     case UO_Imag: {
916       const Expr *Ex = U->getSubExpr()->IgnoreParens();
917       // FIXME: We don't have complex SValues yet.
918       if (Ex->getType()->isAnyComplexType()) {
919         // Just report "Unknown."
920         break;
921       }
922       // For all other types, UO_Imag returns 0.
923       ProgramStateRef state = (*I)->getState();
924       const LocationContext *LCtx = (*I)->getLocationContext();
925       SVal X = svalBuilder.makeZeroVal(Ex->getType());
926       Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
927       break;
928     }
929 
930     case UO_AddrOf: {
931       // Process pointer-to-member address operation.
932       const Expr *Ex = U->getSubExpr()->IgnoreParens();
933       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
934         const ValueDecl *VD = DRE->getDecl();
935 
936         if (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD)) {
937           ProgramStateRef State = (*I)->getState();
938           const LocationContext *LCtx = (*I)->getLocationContext();
939           SVal SV = svalBuilder.getMemberPointer(cast<DeclaratorDecl>(VD));
940           Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
941           break;
942         }
943       }
944       // Explicitly proceed with default handler for this case cascade.
945       handleUOExtension(I, U, Bldr);
946       break;
947     }
948     case UO_Plus:
949       assert(!U->isGLValue());
950       // FALL-THROUGH.
951     case UO_Deref:
952     case UO_Extension: {
953       handleUOExtension(I, U, Bldr);
954       break;
955     }
956 
957     case UO_LNot:
958     case UO_Minus:
959     case UO_Not: {
960       assert (!U->isGLValue());
961       const Expr *Ex = U->getSubExpr()->IgnoreParens();
962       ProgramStateRef state = (*I)->getState();
963       const LocationContext *LCtx = (*I)->getLocationContext();
964 
965       // Get the value of the subexpression.
966       SVal V = state->getSVal(Ex, LCtx);
967 
968       if (V.isUnknownOrUndef()) {
969         Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
970         break;
971       }
972 
973       switch (U->getOpcode()) {
974         default:
975           llvm_unreachable("Invalid Opcode.");
976         case UO_Not:
977           // FIXME: Do we need to handle promotions?
978           state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
979           break;
980         case UO_Minus:
981           // FIXME: Do we need to handle promotions?
982           state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
983           break;
984         case UO_LNot:
985           // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
986           //
987           //  Note: technically we do "E == 0", but this is the same in the
988           //    transfer functions as "0 == E".
989           SVal Result;
990           if (Optional<Loc> LV = V.getAs<Loc>()) {
991             Loc X = svalBuilder.makeNull();
992             Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
993           }
994           else if (Ex->getType()->isFloatingType()) {
995             // FIXME: handle floating point types.
996             Result = UnknownVal();
997           } else {
998             nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
999             Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
1000                                U->getType());
1001           }
1002 
1003           state = state->BindExpr(U, LCtx, Result);
1004           break;
1005       }
1006       Bldr.generateNode(U, *I, state);
1007       break;
1008     }
1009     }
1010   }
1011 
1012   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
1013 }
1014 
1015 void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
1016                                                  ExplodedNode *Pred,
1017                                                  ExplodedNodeSet &Dst) {
1018   // Handle ++ and -- (both pre- and post-increment).
1019   assert (U->isIncrementDecrementOp());
1020   const Expr *Ex = U->getSubExpr()->IgnoreParens();
1021 
1022   const LocationContext *LCtx = Pred->getLocationContext();
1023   ProgramStateRef state = Pred->getState();
1024   SVal loc = state->getSVal(Ex, LCtx);
1025 
1026   // Perform a load.
1027   ExplodedNodeSet Tmp;
1028   evalLoad(Tmp, U, Ex, Pred, state, loc);
1029 
1030   ExplodedNodeSet Dst2;
1031   StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
1032   for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
1033 
1034     state = (*I)->getState();
1035     assert(LCtx == (*I)->getLocationContext());
1036     SVal V2_untested = state->getSVal(Ex, LCtx);
1037 
1038     // Propagate unknown and undefined values.
1039     if (V2_untested.isUnknownOrUndef()) {
1040       Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
1041       continue;
1042     }
1043     DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
1044 
1045     // Handle all other values.
1046     BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
1047 
1048     // If the UnaryOperator has non-location type, use its type to create the
1049     // constant value. If the UnaryOperator has location type, create the
1050     // constant with int type and pointer width.
1051     SVal RHS;
1052 
1053     if (U->getType()->isAnyPointerType())
1054       RHS = svalBuilder.makeArrayIndex(1);
1055     else if (U->getType()->isIntegralOrEnumerationType())
1056       RHS = svalBuilder.makeIntVal(1, U->getType());
1057     else
1058       RHS = UnknownVal();
1059 
1060     SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
1061 
1062     // Conjure a new symbol if necessary to recover precision.
1063     if (Result.isUnknown()){
1064       DefinedOrUnknownSVal SymVal =
1065         svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1066                                      currBldrCtx->blockCount());
1067       Result = SymVal;
1068 
1069       // If the value is a location, ++/-- should always preserve
1070       // non-nullness.  Check if the original value was non-null, and if so
1071       // propagate that constraint.
1072       if (Loc::isLocType(U->getType())) {
1073         DefinedOrUnknownSVal Constraint =
1074         svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
1075 
1076         if (!state->assume(Constraint, true)) {
1077           // It isn't feasible for the original value to be null.
1078           // Propagate this constraint.
1079           Constraint = svalBuilder.evalEQ(state, SymVal,
1080                                        svalBuilder.makeZeroVal(U->getType()));
1081 
1082 
1083           state = state->assume(Constraint, false);
1084           assert(state);
1085         }
1086       }
1087     }
1088 
1089     // Since the lvalue-to-rvalue conversion is explicit in the AST,
1090     // we bind an l-value if the operator is prefix and an lvalue (in C++).
1091     if (U->isGLValue())
1092       state = state->BindExpr(U, LCtx, loc);
1093     else
1094       state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
1095 
1096     // Perform the store.
1097     Bldr.takeNodes(*I);
1098     ExplodedNodeSet Dst3;
1099     evalStore(Dst3, U, U, *I, state, loc, Result);
1100     Bldr.addNodes(Dst3);
1101   }
1102   Dst.insert(Dst2);
1103 }
1104