1 //=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines ExprEngine's support for C expressions.
12 //===----------------------------------------------------------------------===//
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"
19 using namespace clang;
23 /// Optionally conjure and return a symbol for offset when processing
24 /// an expression \p Expression.
25 /// If \p Other is a location, conjure a symbol for \p Symbol
26 /// (offset) if it is unknown so that memory arithmetic always
27 /// results in an ElementRegion.
28 /// \p Count The number of times the current basic block was visited.
29 static SVal conjureOffsetSymbolOnLocation(
30 SVal Symbol, SVal Other, Expr* Expression, SValBuilder &svalBuilder,
31 unsigned Count, const LocationContext *LCtx) {
32 QualType Ty = Expression->getType();
33 if (Other.getAs<Loc>() &&
34 Ty->isIntegralOrEnumerationType() &&
36 return svalBuilder.conjureSymbolVal(Expression, LCtx, Ty, Count);
41 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
43 ExplodedNodeSet &Dst) {
45 Expr *LHS = B->getLHS()->IgnoreParens();
46 Expr *RHS = B->getRHS()->IgnoreParens();
48 // FIXME: Prechecks eventually go in ::Visit().
49 ExplodedNodeSet CheckedSet;
51 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
53 // With both the LHS and RHS evaluated, process the operation itself.
54 for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
57 ProgramStateRef state = (*it)->getState();
58 const LocationContext *LCtx = (*it)->getLocationContext();
59 SVal LeftV = state->getSVal(LHS, LCtx);
60 SVal RightV = state->getSVal(RHS, LCtx);
62 BinaryOperator::Opcode Op = B->getOpcode();
64 if (Op == BO_Assign) {
65 // EXPERIMENTAL: "Conjured" symbols.
66 // FIXME: Handle structs.
67 if (RightV.isUnknown()) {
68 unsigned Count = currBldrCtx->blockCount();
69 RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
72 // Simulate the effects of a "store": bind the value of the RHS
73 // to the L-Value represented by the LHS.
74 SVal ExprVal = B->isGLValue() ? LeftV : RightV;
75 evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
80 if (!B->isAssignmentOp()) {
81 StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
83 if (B->isAdditiveOp()) {
84 // TODO: This can be removed after we enable history tracking with
86 unsigned Count = currBldrCtx->blockCount();
87 RightV = conjureOffsetSymbolOnLocation(
88 RightV, LeftV, RHS, svalBuilder, Count, LCtx);
89 LeftV = conjureOffsetSymbolOnLocation(
90 LeftV, RightV, LHS, svalBuilder, Count, LCtx);
93 // Although we don't yet model pointers-to-members, we do need to make
94 // sure that the members of temporaries have a valid 'this' pointer for
96 if (B->getOpcode() == BO_PtrMemD)
97 state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
99 // Process non-assignments except commas or short-circuited
100 // logical expressions (LAnd and LOr).
101 SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
102 if (!Result.isUnknown()) {
103 state = state->BindExpr(B, LCtx, Result);
106 Bldr.generateNode(B, *it, state);
110 assert (B->isCompoundAssignmentOp());
114 llvm_unreachable("Invalid opcode for compound assignment.");
115 case BO_MulAssign: Op = BO_Mul; break;
116 case BO_DivAssign: Op = BO_Div; break;
117 case BO_RemAssign: Op = BO_Rem; break;
118 case BO_AddAssign: Op = BO_Add; break;
119 case BO_SubAssign: Op = BO_Sub; break;
120 case BO_ShlAssign: Op = BO_Shl; break;
121 case BO_ShrAssign: Op = BO_Shr; break;
122 case BO_AndAssign: Op = BO_And; break;
123 case BO_XorAssign: Op = BO_Xor; break;
124 case BO_OrAssign: Op = BO_Or; break;
127 // Perform a load (the LHS). This performs the checks for
128 // null dereferences, and so on.
130 SVal location = LeftV;
131 evalLoad(Tmp, B, LHS, *it, state, location);
133 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
136 state = (*I)->getState();
137 const LocationContext *LCtx = (*I)->getLocationContext();
138 SVal V = state->getSVal(LHS, LCtx);
140 // Get the computation type.
142 cast<CompoundAssignOperator>(B)->getComputationResultType();
143 CTy = getContext().getCanonicalType(CTy);
146 cast<CompoundAssignOperator>(B)->getComputationLHSType();
147 CLHSTy = getContext().getCanonicalType(CLHSTy);
149 QualType LTy = getContext().getCanonicalType(LHS->getType());
152 V = svalBuilder.evalCast(V, CLHSTy, LTy);
154 // Compute the result of the operation.
155 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
158 // EXPERIMENTAL: "Conjured" symbols.
159 // FIXME: Handle structs.
163 if (Result.isUnknown()) {
164 // The symbolic value is actually for the type of the left-hand side
165 // expression, not the computation type, as this is the value the
166 // LValue on the LHS will bind to.
167 LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
168 currBldrCtx->blockCount());
169 // However, we need to convert the symbol to the computation type.
170 Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
173 // The left-hand side may bind to a different value then the
175 LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
178 // In C++, assignment and compound assignment operators return an
181 state = state->BindExpr(B, LCtx, location);
183 state = state->BindExpr(B, LCtx, Result);
185 evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
189 // FIXME: postvisits eventually go in ::Visit()
190 getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
193 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
194 ExplodedNodeSet &Dst) {
196 CanQualType T = getContext().getCanonicalType(BE->getType());
198 const BlockDecl *BD = BE->getBlockDecl();
199 // Get the value of the block itself.
200 SVal V = svalBuilder.getBlockPointer(BD, T,
201 Pred->getLocationContext(),
202 currBldrCtx->blockCount());
204 ProgramStateRef State = Pred->getState();
206 // If we created a new MemRegion for the block, we should explicitly bind
207 // the captured variables.
208 if (const BlockDataRegion *BDR =
209 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
211 BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
212 E = BDR->referenced_vars_end();
214 auto CI = BD->capture_begin();
215 auto CE = BD->capture_end();
216 for (; I != E; ++I) {
217 const VarRegion *capturedR = I.getCapturedRegion();
218 const VarRegion *originalR = I.getOriginalRegion();
220 // If the capture had a copy expression, use the result of evaluating
221 // that expression, otherwise use the original value.
222 // We rely on the invariant that the block declaration's capture variables
223 // are a prefix of the BlockDataRegion's referenced vars (which may include
224 // referenced globals, etc.) to enable fast lookup of the capture for a
225 // given referenced var.
226 const Expr *copyExpr = nullptr;
228 assert(CI->getVariable() == capturedR->getDecl());
229 copyExpr = CI->getCopyExpr();
233 if (capturedR != originalR) {
235 const LocationContext *LCtx = Pred->getLocationContext();
237 originalV = State->getSVal(copyExpr, LCtx);
239 originalV = State->getSVal(loc::MemRegionVal(originalR));
241 State = State->bindLoc(loc::MemRegionVal(capturedR), originalV, LCtx);
247 StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
248 Bldr.generateNode(BE, Pred,
249 State->BindExpr(BE, Pred->getLocationContext(), V),
250 nullptr, ProgramPoint::PostLValueKind);
252 // FIXME: Move all post/pre visits to ::Visit().
253 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
256 ProgramStateRef ExprEngine::handleLValueBitCast(
257 ProgramStateRef state, const Expr* Ex, const LocationContext* LCtx,
258 QualType T, QualType ExTy, const CastExpr* CastE, StmtNodeBuilder& Bldr,
259 ExplodedNode* Pred) {
260 if (T->isLValueReferenceType()) {
261 assert(!CastE->getType()->isLValueReferenceType());
262 ExTy = getContext().getLValueReferenceType(ExTy);
263 } else if (T->isRValueReferenceType()) {
264 assert(!CastE->getType()->isRValueReferenceType());
265 ExTy = getContext().getRValueReferenceType(ExTy);
267 // Delegate to SValBuilder to process.
268 SVal OrigV = state->getSVal(Ex, LCtx);
269 SVal V = svalBuilder.evalCast(OrigV, T, ExTy);
270 // Negate the result if we're treating the boolean as a signed i1
271 if (CastE->getCastKind() == CK_BooleanToSignedIntegral)
273 state = state->BindExpr(CastE, LCtx, V);
274 if (V.isUnknown() && !OrigV.isUnknown()) {
275 state = escapeValue(state, OrigV, PSK_EscapeOther);
277 Bldr.generateNode(CastE, Pred, state);
282 ProgramStateRef ExprEngine::handleLVectorSplat(
283 ProgramStateRef state, const LocationContext* LCtx, const CastExpr* CastE,
284 StmtNodeBuilder &Bldr, ExplodedNode* Pred) {
285 // Recover some path sensitivity by conjuring a new value.
286 QualType resultType = CastE->getType();
287 if (CastE->isGLValue())
288 resultType = getContext().getPointerType(resultType);
289 SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx,
291 currBldrCtx->blockCount());
292 state = state->BindExpr(CastE, LCtx, result);
293 Bldr.generateNode(CastE, Pred, state);
298 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
299 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
301 ExplodedNodeSet dstPreStmt;
302 getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
304 if (CastE->getCastKind() == CK_LValueToRValue) {
305 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
307 ExplodedNode *subExprNode = *I;
308 ProgramStateRef state = subExprNode->getState();
309 const LocationContext *LCtx = subExprNode->getLocationContext();
310 evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
316 QualType T = CastE->getType();
317 QualType ExTy = Ex->getType();
319 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
320 T = ExCast->getTypeAsWritten();
322 StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
323 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
327 ProgramStateRef state = Pred->getState();
328 const LocationContext *LCtx = Pred->getLocationContext();
330 switch (CastE->getCastKind()) {
331 case CK_LValueToRValue:
332 llvm_unreachable("LValueToRValue casts handled earlier.");
335 // The analyzer doesn't do anything special with these casts,
336 // since it understands retain/release semantics already.
337 case CK_ARCProduceObject:
338 case CK_ARCConsumeObject:
339 case CK_ARCReclaimReturnedObject:
340 case CK_ARCExtendBlockObject: // Fall-through.
341 case CK_CopyAndAutoreleaseBlockObject:
342 // The analyser can ignore atomic casts for now, although some future
343 // checkers may want to make certain that you're not modifying the same
344 // value through atomic and nonatomic pointers.
345 case CK_AtomicToNonAtomic:
346 case CK_NonAtomicToAtomic:
349 case CK_ConstructorConversion:
350 case CK_UserDefinedConversion:
351 case CK_FunctionToPointerDecay:
352 case CK_BuiltinFnToFnPtr: {
353 // Copy the SVal of Ex to CastE.
354 ProgramStateRef state = Pred->getState();
355 const LocationContext *LCtx = Pred->getLocationContext();
356 SVal V = state->getSVal(Ex, LCtx);
357 state = state->BindExpr(CastE, LCtx, V);
358 Bldr.generateNode(CastE, Pred, state);
361 case CK_MemberPointerToBoolean:
362 case CK_PointerToBoolean: {
363 SVal V = state->getSVal(Ex, LCtx);
364 auto PTMSV = V.getAs<nonloc::PointerToMember>();
366 V = svalBuilder.makeTruthVal(!PTMSV->isNullMemberPointer(), ExTy);
367 if (V.isUndef() || PTMSV) {
368 state = state->BindExpr(CastE, LCtx, V);
369 Bldr.generateNode(CastE, Pred, state);
372 // Explicitly proceed with default handler for this case cascade.
374 handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
378 case CK_ArrayToPointerDecay:
380 case CK_AddressSpaceConversion:
381 case CK_BooleanToSignedIntegral:
382 case CK_NullToPointer:
383 case CK_IntegralToPointer:
384 case CK_PointerToIntegral: {
385 SVal V = state->getSVal(Ex, LCtx);
386 if (V.getAs<nonloc::PointerToMember>()) {
387 state = state->BindExpr(CastE, LCtx, UnknownVal());
388 Bldr.generateNode(CastE, Pred, state);
391 // Explicitly proceed with default handler for this case cascade.
393 handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
396 case CK_IntegralToBoolean:
397 case CK_IntegralToFloating:
398 case CK_FloatingToIntegral:
399 case CK_FloatingToBoolean:
400 case CK_FloatingCast:
401 case CK_FloatingRealToComplex:
402 case CK_FloatingComplexToReal:
403 case CK_FloatingComplexToBoolean:
404 case CK_FloatingComplexCast:
405 case CK_FloatingComplexToIntegralComplex:
406 case CK_IntegralRealToComplex:
407 case CK_IntegralComplexToReal:
408 case CK_IntegralComplexToBoolean:
409 case CK_IntegralComplexCast:
410 case CK_IntegralComplexToFloatingComplex:
411 case CK_CPointerToObjCPointerCast:
412 case CK_BlockPointerToObjCPointerCast:
413 case CK_AnyPointerToBlockPointerCast:
414 case CK_ObjCObjectLValueCast:
415 case CK_ZeroToOCLOpaqueType:
416 case CK_IntToOCLSampler:
417 case CK_LValueBitCast:
418 case CK_FixedPointCast:
419 case CK_FixedPointToBoolean: {
421 handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
424 case CK_IntegralCast: {
425 // Delegate to SValBuilder to process.
426 SVal V = state->getSVal(Ex, LCtx);
427 V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
428 state = state->BindExpr(CastE, LCtx, V);
429 Bldr.generateNode(CastE, Pred, state);
432 case CK_DerivedToBase:
433 case CK_UncheckedDerivedToBase: {
434 // For DerivedToBase cast, delegate to the store manager.
435 SVal val = state->getSVal(Ex, LCtx);
436 val = getStoreManager().evalDerivedToBase(val, CastE);
437 state = state->BindExpr(CastE, LCtx, val);
438 Bldr.generateNode(CastE, Pred, state);
441 // Handle C++ dyn_cast.
443 SVal val = state->getSVal(Ex, LCtx);
445 // Compute the type of the result.
446 QualType resultType = CastE->getType();
447 if (CastE->isGLValue())
448 resultType = getContext().getPointerType(resultType);
452 // Check if the value being cast evaluates to 0.
453 if (val.isZeroConstant())
455 // Else, evaluate the cast.
457 val = getStoreManager().attemptDownCast(val, T, Failed);
460 if (T->isReferenceType()) {
461 // A bad_cast exception is thrown if input value is a reference.
462 // Currently, we model this, by generating a sink.
463 Bldr.generateSink(CastE, Pred, state);
466 // If the cast fails on a pointer, bind to 0.
467 state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
470 // If we don't know if the cast succeeded, conjure a new symbol.
471 if (val.isUnknown()) {
472 DefinedOrUnknownSVal NewSym =
473 svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
474 currBldrCtx->blockCount());
475 state = state->BindExpr(CastE, LCtx, NewSym);
477 // Else, bind to the derived region value.
478 state = state->BindExpr(CastE, LCtx, val);
480 Bldr.generateNode(CastE, Pred, state);
483 case CK_BaseToDerived: {
484 SVal val = state->getSVal(Ex, LCtx);
485 QualType resultType = CastE->getType();
486 if (CastE->isGLValue())
487 resultType = getContext().getPointerType(resultType);
491 if (!val.isConstant()) {
492 val = getStoreManager().attemptDownCast(val, T, Failed);
495 // Failed to cast or the result is unknown, fall back to conservative.
496 if (Failed || val.isUnknown()) {
498 svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
499 currBldrCtx->blockCount());
501 state = state->BindExpr(CastE, LCtx, val);
502 Bldr.generateNode(CastE, Pred, state);
505 case CK_NullToMemberPointer: {
506 SVal V = svalBuilder.getMemberPointer(nullptr);
507 state = state->BindExpr(CastE, LCtx, V);
508 Bldr.generateNode(CastE, Pred, state);
511 case CK_DerivedToBaseMemberPointer:
512 case CK_BaseToDerivedMemberPointer:
513 case CK_ReinterpretMemberPointer: {
514 SVal V = state->getSVal(Ex, LCtx);
515 if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) {
516 SVal CastedPTMSV = svalBuilder.makePointerToMember(
517 getBasicVals().accumCXXBase(
518 llvm::make_range<CastExpr::path_const_iterator>(
519 CastE->path_begin(), CastE->path_end()), *PTMSV));
520 state = state->BindExpr(CastE, LCtx, CastedPTMSV);
521 Bldr.generateNode(CastE, Pred, state);
524 // Explicitly proceed with default handler for this case cascade.
525 state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
528 // Various C++ casts that are not handled yet.
530 case CK_VectorSplat: {
531 state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
538 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
540 ExplodedNodeSet &Dst) {
541 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
543 ProgramStateRef State = Pred->getState();
544 const LocationContext *LCtx = Pred->getLocationContext();
546 const Expr *Init = CL->getInitializer();
547 SVal V = State->getSVal(CL->getInitializer(), LCtx);
549 if (isa<CXXConstructExpr>(Init) || isa<CXXStdInitializerListExpr>(Init)) {
550 // No work needed. Just pass the value up to this expression.
552 assert(isa<InitListExpr>(Init));
553 Loc CLLoc = State->getLValue(CL, LCtx);
554 State = State->bindLoc(CLLoc, V, LCtx);
560 B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
563 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
564 ExplodedNodeSet &Dst) {
565 // Assumption: The CFG has one DeclStmt per Decl.
566 const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
569 //TODO:AZ: remove explicit insertion after refactoring is done.
574 // FIXME: all pre/post visits should eventually be handled by ::Visit().
575 ExplodedNodeSet dstPreVisit;
576 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
578 ExplodedNodeSet dstEvaluated;
579 StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
580 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
582 ExplodedNode *N = *I;
583 ProgramStateRef state = N->getState();
584 const LocationContext *LC = N->getLocationContext();
586 // Decls without InitExpr are not initialized explicitly.
587 if (const Expr *InitEx = VD->getInit()) {
589 // Note in the state that the initialization has occurred.
590 ExplodedNode *UpdatedN = N;
591 SVal InitVal = state->getSVal(InitEx, LC);
593 assert(DS->isSingleDecl());
594 if (getObjectUnderConstruction(state, DS, LC)) {
595 state = finishObjectConstruction(state, DS, LC);
596 // We constructed the object directly in the variable.
597 // No need to bind anything.
598 B.generateNode(DS, UpdatedN, state);
600 // Recover some path-sensitivity if a scalar value evaluated to
602 if (InitVal.isUnknown()) {
603 QualType Ty = InitEx->getType();
604 if (InitEx->isGLValue()) {
605 Ty = getContext().getPointerType(Ty);
608 InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
609 currBldrCtx->blockCount());
613 B.takeNodes(UpdatedN);
614 ExplodedNodeSet Dst2;
615 evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
620 B.generateNode(DS, N, state);
624 getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
627 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
628 ExplodedNodeSet &Dst) {
629 assert(B->getOpcode() == BO_LAnd ||
630 B->getOpcode() == BO_LOr);
632 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
633 ProgramStateRef state = Pred->getState();
635 if (B->getType()->isVectorType()) {
636 // FIXME: We do not model vector arithmetic yet. When adding support for
637 // that, note that the CFG-based reasoning below does not apply, because
638 // logical operators on vectors are not short-circuit. Currently they are
639 // modeled as short-circuit in Clang CFG but this is incorrect.
640 // Do not set the value for the expression. It'd be UnknownVal by default.
641 Bldr.generateNode(B, Pred, state);
645 ExplodedNode *N = Pred;
646 while (!N->getLocation().getAs<BlockEntrance>()) {
647 ProgramPoint P = N->getLocation();
648 assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
650 assert(N->pred_size() == 1);
651 N = *N->pred_begin();
653 assert(N->pred_size() == 1);
654 N = *N->pred_begin();
655 BlockEdge BE = N->getLocation().castAs<BlockEdge>();
658 // Determine the value of the expression by introspecting how we
659 // got this location in the CFG. This requires looking at the previous
660 // block we were in and what kind of control-flow transfer was involved.
661 const CFGBlock *SrcBlock = BE.getSrc();
662 // The only terminator (if there is one) that makes sense is a logical op.
663 CFGTerminator T = SrcBlock->getTerminator();
664 if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
666 assert(Term->isLogicalOp());
667 assert(SrcBlock->succ_size() == 2);
668 // Did we take the true or false branch?
669 unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
670 X = svalBuilder.makeIntVal(constant, B->getType());
673 // If there is no terminator, by construction the last statement
674 // in SrcBlock is the value of the enclosing expression.
675 // However, we still need to constrain that value to be 0 or 1.
676 assert(!SrcBlock->empty());
677 CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
678 const Expr *RHS = cast<Expr>(Elem.getStmt());
679 SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
681 if (RHSVal.isUndef()) {
684 // We evaluate "RHSVal != 0" expression which result in 0 if the value is
685 // known to be false, 1 if the value is known to be true and a new symbol
686 // when the assumption is unknown.
687 nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType()));
688 X = evalBinOp(N->getState(), BO_NE,
689 svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()),
693 Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
696 void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
698 ExplodedNodeSet &Dst) {
699 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
701 ProgramStateRef state = Pred->getState();
702 const LocationContext *LCtx = Pred->getLocationContext();
703 QualType T = getContext().getCanonicalType(IE->getType());
704 unsigned NumInitElements = IE->getNumInits();
706 if (!IE->isGLValue() &&
707 (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
708 T->isAnyComplexType())) {
709 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
711 // Handle base case where the initializer has no elements.
712 // e.g: static int* myArray[] = {};
713 if (NumInitElements == 0) {
714 SVal V = svalBuilder.makeCompoundVal(T, vals);
715 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
719 for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
720 ei = IE->rend(); it != ei; ++it) {
721 SVal V = state->getSVal(cast<Expr>(*it), LCtx);
722 vals = getBasicVals().prependSVal(V, vals);
725 B.generateNode(IE, Pred,
726 state->BindExpr(IE, LCtx,
727 svalBuilder.makeCompoundVal(T, vals)));
731 // Handle scalars: int{5} and int{} and GLvalues.
732 // Note, if the InitListExpr is a GLvalue, it means that there is an address
733 // representing it, so it must have a single init element.
734 assert(NumInitElements <= 1);
737 if (NumInitElements == 0)
738 V = getSValBuilder().makeZeroVal(T);
740 V = state->getSVal(IE->getInit(0), LCtx);
742 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
745 void ExprEngine::VisitGuardedExpr(const Expr *Ex,
749 ExplodedNodeSet &Dst) {
752 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
753 ProgramStateRef state = Pred->getState();
754 const LocationContext *LCtx = Pred->getLocationContext();
755 const CFGBlock *SrcBlock = nullptr;
757 // Find the predecessor block.
758 ProgramStateRef SrcState = state;
759 for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
760 ProgramPoint PP = N->getLocation();
761 if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
762 // If the state N has multiple predecessors P, it means that successors
763 // of P are all equivalent.
764 // In turn, that means that all nodes at P are equivalent in terms
765 // of observable behavior at N, and we can follow any of them.
766 // FIXME: a more robust solution which does not walk up the tree.
769 SrcBlock = PP.castAs<BlockEdge>().getSrc();
770 SrcState = N->getState();
774 assert(SrcBlock && "missing function entry");
776 // Find the last expression in the predecessor block. That is the
777 // expression that is used for the value of the ternary expression.
778 bool hasValue = false;
781 for (CFGElement CE : llvm::reverse(*SrcBlock)) {
782 if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
783 const Expr *ValEx = cast<Expr>(CS->getStmt());
784 ValEx = ValEx->IgnoreParens();
786 // For GNU extension '?:' operator, the left hand side will be an
787 // OpaqueValueExpr, so get the underlying expression.
788 if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
789 L = OpaqueEx->getSourceExpr();
791 // If the last expression in the predecessor block matches true or false
792 // subexpression, get its the value.
793 if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
795 V = SrcState->getSVal(ValEx, LCtx);
802 V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
803 currBldrCtx->blockCount());
805 // Generate a new node with the binding from the appropriate path.
806 B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
810 VisitOffsetOfExpr(const OffsetOfExpr *OOE,
811 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
812 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
813 Expr::EvalResult Result;
814 if (OOE->EvaluateAsInt(Result, getContext())) {
815 APSInt IV = Result.Val.getInt();
816 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
817 assert(OOE->getType()->isBuiltinType());
818 assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
819 assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
820 SVal X = svalBuilder.makeIntVal(IV);
821 B.generateNode(OOE, Pred,
822 Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
825 // FIXME: Handle the case where __builtin_offsetof is not a constant.
830 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
832 ExplodedNodeSet &Dst) {
833 // FIXME: Prechecks eventually go in ::Visit().
834 ExplodedNodeSet CheckedSet;
835 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
837 ExplodedNodeSet EvalSet;
838 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
840 QualType T = Ex->getTypeOfArgument();
842 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
844 if (Ex->getKind() == UETT_SizeOf) {
845 if (!T->isIncompleteType() && !T->isConstantSizeType()) {
846 assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
848 // FIXME: Add support for VLA type arguments and VLA expressions.
849 // When that happens, we should probably refactor VLASizeChecker's code.
851 } else if (T->getAs<ObjCObjectType>()) {
852 // Some code tries to take the sizeof an ObjCObjectType, relying that
853 // the compiler has laid out its representation. Just report Unknown
859 APSInt Value = Ex->EvaluateKnownConstInt(getContext());
860 CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
862 ProgramStateRef state = (*I)->getState();
863 state = state->BindExpr(Ex, (*I)->getLocationContext(),
864 svalBuilder.makeIntVal(amt.getQuantity(),
866 Bldr.generateNode(Ex, *I, state);
869 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
872 void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
873 const UnaryOperator *U,
874 StmtNodeBuilder &Bldr) {
875 // FIXME: We can probably just have some magic in Environment::getSVal()
876 // that propagates values, instead of creating a new node here.
878 // Unary "+" is a no-op, similar to a parentheses. We still have places
879 // where it may be a block-level expression, so we need to
880 // generate an extra node that just propagates the value of the
882 const Expr *Ex = U->getSubExpr()->IgnoreParens();
883 ProgramStateRef state = (*I)->getState();
884 const LocationContext *LCtx = (*I)->getLocationContext();
885 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
886 state->getSVal(Ex, LCtx)));
889 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
890 ExplodedNodeSet &Dst) {
891 // FIXME: Prechecks eventually go in ::Visit().
892 ExplodedNodeSet CheckedSet;
893 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
895 ExplodedNodeSet EvalSet;
896 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
898 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
900 switch (U->getOpcode()) {
904 VisitIncrementDecrementOperator(U, *I, Tmp);
909 const Expr *Ex = U->getSubExpr()->IgnoreParens();
911 // FIXME: We don't have complex SValues yet.
912 if (Ex->getType()->isAnyComplexType()) {
913 // Just report "Unknown."
917 // For all other types, UO_Real is an identity operation.
918 assert (U->getType() == Ex->getType());
919 ProgramStateRef state = (*I)->getState();
920 const LocationContext *LCtx = (*I)->getLocationContext();
921 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
922 state->getSVal(Ex, LCtx)));
927 const Expr *Ex = U->getSubExpr()->IgnoreParens();
928 // FIXME: We don't have complex SValues yet.
929 if (Ex->getType()->isAnyComplexType()) {
930 // Just report "Unknown."
933 // For all other types, UO_Imag returns 0.
934 ProgramStateRef state = (*I)->getState();
935 const LocationContext *LCtx = (*I)->getLocationContext();
936 SVal X = svalBuilder.makeZeroVal(Ex->getType());
937 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
942 // Process pointer-to-member address operation.
943 const Expr *Ex = U->getSubExpr()->IgnoreParens();
944 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
945 const ValueDecl *VD = DRE->getDecl();
947 if (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD)) {
948 ProgramStateRef State = (*I)->getState();
949 const LocationContext *LCtx = (*I)->getLocationContext();
950 SVal SV = svalBuilder.getMemberPointer(cast<DeclaratorDecl>(VD));
951 Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
955 // Explicitly proceed with default handler for this case cascade.
956 handleUOExtension(I, U, Bldr);
960 assert(!U->isGLValue());
964 handleUOExtension(I, U, Bldr);
971 assert (!U->isGLValue());
972 const Expr *Ex = U->getSubExpr()->IgnoreParens();
973 ProgramStateRef state = (*I)->getState();
974 const LocationContext *LCtx = (*I)->getLocationContext();
976 // Get the value of the subexpression.
977 SVal V = state->getSVal(Ex, LCtx);
979 if (V.isUnknownOrUndef()) {
980 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
984 switch (U->getOpcode()) {
986 llvm_unreachable("Invalid Opcode.");
988 // FIXME: Do we need to handle promotions?
989 state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
992 // FIXME: Do we need to handle promotions?
993 state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
996 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
998 // Note: technically we do "E == 0", but this is the same in the
999 // transfer functions as "0 == E".
1001 if (Optional<Loc> LV = V.getAs<Loc>()) {
1002 Loc X = svalBuilder.makeNullWithType(Ex->getType());
1003 Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
1004 } else if (Ex->getType()->isFloatingType()) {
1005 // FIXME: handle floating point types.
1006 Result = UnknownVal();
1008 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
1009 Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
1013 state = state->BindExpr(U, LCtx, Result);
1016 Bldr.generateNode(U, *I, state);
1022 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
1025 void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
1027 ExplodedNodeSet &Dst) {
1028 // Handle ++ and -- (both pre- and post-increment).
1029 assert (U->isIncrementDecrementOp());
1030 const Expr *Ex = U->getSubExpr()->IgnoreParens();
1032 const LocationContext *LCtx = Pred->getLocationContext();
1033 ProgramStateRef state = Pred->getState();
1034 SVal loc = state->getSVal(Ex, LCtx);
1037 ExplodedNodeSet Tmp;
1038 evalLoad(Tmp, U, Ex, Pred, state, loc);
1040 ExplodedNodeSet Dst2;
1041 StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
1042 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
1044 state = (*I)->getState();
1045 assert(LCtx == (*I)->getLocationContext());
1046 SVal V2_untested = state->getSVal(Ex, LCtx);
1048 // Propagate unknown and undefined values.
1049 if (V2_untested.isUnknownOrUndef()) {
1050 state = state->BindExpr(U, LCtx, V2_untested);
1052 // Perform the store, so that the uninitialized value detection happens.
1054 ExplodedNodeSet Dst3;
1055 evalStore(Dst3, U, Ex, *I, state, loc, V2_untested);
1056 Bldr.addNodes(Dst3);
1060 DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
1062 // Handle all other values.
1063 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
1065 // If the UnaryOperator has non-location type, use its type to create the
1066 // constant value. If the UnaryOperator has location type, create the
1067 // constant with int type and pointer width.
1071 if (U->getType()->isAnyPointerType())
1072 RHS = svalBuilder.makeArrayIndex(1);
1073 else if (U->getType()->isIntegralOrEnumerationType())
1074 RHS = svalBuilder.makeIntVal(1, U->getType());
1078 // The use of an operand of type bool with the ++ operators is deprecated
1079 // but valid until C++17. And if the operand of the ++ operator is of type
1080 // bool, it is set to true until C++17. Note that for '_Bool', it is also
1081 // set to true when it encounters ++ operator.
1082 if (U->getType()->isBooleanType() && U->isIncrementOp())
1083 Result = svalBuilder.makeTruthVal(true, U->getType());
1085 Result = evalBinOp(state, Op, V2, RHS, U->getType());
1087 // Conjure a new symbol if necessary to recover precision.
1088 if (Result.isUnknown()){
1089 DefinedOrUnknownSVal SymVal =
1090 svalBuilder.conjureSymbolVal(nullptr, U, LCtx,
1091 currBldrCtx->blockCount());
1094 // If the value is a location, ++/-- should always preserve
1095 // non-nullness. Check if the original value was non-null, and if so
1096 // propagate that constraint.
1097 if (Loc::isLocType(U->getType())) {
1098 DefinedOrUnknownSVal Constraint =
1099 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
1101 if (!state->assume(Constraint, true)) {
1102 // It isn't feasible for the original value to be null.
1103 // Propagate this constraint.
1104 Constraint = svalBuilder.evalEQ(state, SymVal,
1105 svalBuilder.makeZeroVal(U->getType()));
1107 state = state->assume(Constraint, false);
1113 // Since the lvalue-to-rvalue conversion is explicit in the AST,
1114 // we bind an l-value if the operator is prefix and an lvalue (in C++).
1116 state = state->BindExpr(U, LCtx, loc);
1118 state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
1120 // Perform the store.
1122 ExplodedNodeSet Dst3;
1123 evalStore(Dst3, U, Ex, *I, state, loc, Result);
1124 Bldr.addNodes(Dst3);