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/StaticAnalyzer/Core/CheckerManager.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
18 using namespace clang;
22 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
24 ExplodedNodeSet &Dst) {
26 Expr *LHS = B->getLHS()->IgnoreParens();
27 Expr *RHS = B->getRHS()->IgnoreParens();
29 // FIXME: Prechecks eventually go in ::Visit().
30 ExplodedNodeSet CheckedSet;
32 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
34 // With both the LHS and RHS evaluated, process the operation itself.
35 for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
38 ProgramStateRef state = (*it)->getState();
39 const LocationContext *LCtx = (*it)->getLocationContext();
40 SVal LeftV = state->getSVal(LHS, LCtx);
41 SVal RightV = state->getSVal(RHS, LCtx);
43 BinaryOperator::Opcode Op = B->getOpcode();
45 if (Op == BO_Assign) {
46 // EXPERIMENTAL: "Conjured" symbols.
47 // FIXME: Handle structs.
48 if (RightV.isUnknown()) {
49 unsigned Count = currBldrCtx->blockCount();
50 RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
53 // Simulate the effects of a "store": bind the value of the RHS
54 // to the L-Value represented by the LHS.
55 SVal ExprVal = B->isGLValue() ? LeftV : RightV;
56 evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
61 if (!B->isAssignmentOp()) {
62 StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
64 if (B->isAdditiveOp()) {
65 // If one of the operands is a location, conjure a symbol for the other
66 // one (offset) if it's unknown so that memory arithmetic always
67 // results in an ElementRegion.
68 // TODO: This can be removed after we enable history tracking with
70 unsigned Count = currBldrCtx->blockCount();
71 if (LeftV.getAs<Loc>() &&
72 RHS->getType()->isIntegralOrEnumerationType() &&
74 RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(),
77 if (RightV.getAs<Loc>() &&
78 LHS->getType()->isIntegralOrEnumerationType() &&
80 LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(),
85 // Although we don't yet model pointers-to-members, we do need to make
86 // sure that the members of temporaries have a valid 'this' pointer for
88 if (B->getOpcode() == BO_PtrMemD)
89 state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
91 // Process non-assignments except commas or short-circuited
92 // logical expressions (LAnd and LOr).
93 SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
94 if (Result.isUnknown()) {
95 Bldr.generateNode(B, *it, state);
99 state = state->BindExpr(B, LCtx, Result);
100 Bldr.generateNode(B, *it, state);
104 assert (B->isCompoundAssignmentOp());
108 llvm_unreachable("Invalid opcode for compound assignment.");
109 case BO_MulAssign: Op = BO_Mul; break;
110 case BO_DivAssign: Op = BO_Div; break;
111 case BO_RemAssign: Op = BO_Rem; break;
112 case BO_AddAssign: Op = BO_Add; break;
113 case BO_SubAssign: Op = BO_Sub; break;
114 case BO_ShlAssign: Op = BO_Shl; break;
115 case BO_ShrAssign: Op = BO_Shr; break;
116 case BO_AndAssign: Op = BO_And; break;
117 case BO_XorAssign: Op = BO_Xor; break;
118 case BO_OrAssign: Op = BO_Or; break;
121 // Perform a load (the LHS). This performs the checks for
122 // null dereferences, and so on.
124 SVal location = LeftV;
125 evalLoad(Tmp, B, LHS, *it, state, location);
127 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
130 state = (*I)->getState();
131 const LocationContext *LCtx = (*I)->getLocationContext();
132 SVal V = state->getSVal(LHS, LCtx);
134 // Get the computation type.
136 cast<CompoundAssignOperator>(B)->getComputationResultType();
137 CTy = getContext().getCanonicalType(CTy);
140 cast<CompoundAssignOperator>(B)->getComputationLHSType();
141 CLHSTy = getContext().getCanonicalType(CLHSTy);
143 QualType LTy = getContext().getCanonicalType(LHS->getType());
146 V = svalBuilder.evalCast(V, CLHSTy, LTy);
148 // Compute the result of the operation.
149 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
152 // EXPERIMENTAL: "Conjured" symbols.
153 // FIXME: Handle structs.
157 if (Result.isUnknown()) {
158 // The symbolic value is actually for the type of the left-hand side
159 // expression, not the computation type, as this is the value the
160 // LValue on the LHS will bind to.
161 LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
162 currBldrCtx->blockCount());
163 // However, we need to convert the symbol to the computation type.
164 Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
167 // The left-hand side may bind to a different value then the
169 LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
172 // In C++, assignment and compound assignment operators return an
175 state = state->BindExpr(B, LCtx, location);
177 state = state->BindExpr(B, LCtx, Result);
179 evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
183 // FIXME: postvisits eventually go in ::Visit()
184 getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
187 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
188 ExplodedNodeSet &Dst) {
190 CanQualType T = getContext().getCanonicalType(BE->getType());
192 const BlockDecl *BD = BE->getBlockDecl();
193 // Get the value of the block itself.
194 SVal V = svalBuilder.getBlockPointer(BD, T,
195 Pred->getLocationContext(),
196 currBldrCtx->blockCount());
198 ProgramStateRef State = Pred->getState();
200 // If we created a new MemRegion for the block, we should explicitly bind
201 // the captured variables.
202 if (const BlockDataRegion *BDR =
203 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
205 BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
206 E = BDR->referenced_vars_end();
208 auto CI = BD->capture_begin();
209 auto CE = BD->capture_end();
210 for (; I != E; ++I) {
211 const VarRegion *capturedR = I.getCapturedRegion();
212 const VarRegion *originalR = I.getOriginalRegion();
214 // If the capture had a copy expression, use the result of evaluating
215 // that expression, otherwise use the original value.
216 // We rely on the invariant that the block declaration's capture variables
217 // are a prefix of the BlockDataRegion's referenced vars (which may include
218 // referenced globals, etc.) to enable fast lookup of the capture for a
219 // given referenced var.
220 const Expr *copyExpr = nullptr;
222 assert(CI->getVariable() == capturedR->getDecl());
223 copyExpr = CI->getCopyExpr();
227 if (capturedR != originalR) {
230 originalV = State->getSVal(copyExpr, Pred->getLocationContext());
232 originalV = State->getSVal(loc::MemRegionVal(originalR));
234 State = State->bindLoc(loc::MemRegionVal(capturedR), originalV);
240 StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
241 Bldr.generateNode(BE, Pred,
242 State->BindExpr(BE, Pred->getLocationContext(), V),
243 nullptr, ProgramPoint::PostLValueKind);
245 // FIXME: Move all post/pre visits to ::Visit().
246 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
249 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
250 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
252 ExplodedNodeSet dstPreStmt;
253 getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
255 if (CastE->getCastKind() == CK_LValueToRValue) {
256 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
258 ExplodedNode *subExprNode = *I;
259 ProgramStateRef state = subExprNode->getState();
260 const LocationContext *LCtx = subExprNode->getLocationContext();
261 evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
267 QualType T = CastE->getType();
268 QualType ExTy = Ex->getType();
270 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
271 T = ExCast->getTypeAsWritten();
273 StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
274 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
278 ProgramStateRef state = Pred->getState();
279 const LocationContext *LCtx = Pred->getLocationContext();
281 switch (CastE->getCastKind()) {
282 case CK_LValueToRValue:
283 llvm_unreachable("LValueToRValue casts handled earlier.");
286 // The analyzer doesn't do anything special with these casts,
287 // since it understands retain/release semantics already.
288 case CK_ARCProduceObject:
289 case CK_ARCConsumeObject:
290 case CK_ARCReclaimReturnedObject:
291 case CK_ARCExtendBlockObject: // Fall-through.
292 case CK_CopyAndAutoreleaseBlockObject:
293 // The analyser can ignore atomic casts for now, although some future
294 // checkers may want to make certain that you're not modifying the same
295 // value through atomic and nonatomic pointers.
296 case CK_AtomicToNonAtomic:
297 case CK_NonAtomicToAtomic:
300 case CK_ConstructorConversion:
301 case CK_UserDefinedConversion:
302 case CK_FunctionToPointerDecay:
303 case CK_BuiltinFnToFnPtr: {
304 // Copy the SVal of Ex to CastE.
305 ProgramStateRef state = Pred->getState();
306 const LocationContext *LCtx = Pred->getLocationContext();
307 SVal V = state->getSVal(Ex, LCtx);
308 state = state->BindExpr(CastE, LCtx, V);
309 Bldr.generateNode(CastE, Pred, state);
312 case CK_MemberPointerToBoolean:
313 // FIXME: For now, member pointers are represented by void *.
316 case CK_ArrayToPointerDecay:
318 case CK_AddressSpaceConversion:
319 case CK_BooleanToSignedIntegral:
320 case CK_NullToPointer:
321 case CK_IntegralToPointer:
322 case CK_PointerToIntegral:
323 case CK_PointerToBoolean:
324 case CK_IntegralToBoolean:
325 case CK_IntegralToFloating:
326 case CK_FloatingToIntegral:
327 case CK_FloatingToBoolean:
328 case CK_FloatingCast:
329 case CK_FloatingRealToComplex:
330 case CK_FloatingComplexToReal:
331 case CK_FloatingComplexToBoolean:
332 case CK_FloatingComplexCast:
333 case CK_FloatingComplexToIntegralComplex:
334 case CK_IntegralRealToComplex:
335 case CK_IntegralComplexToReal:
336 case CK_IntegralComplexToBoolean:
337 case CK_IntegralComplexCast:
338 case CK_IntegralComplexToFloatingComplex:
339 case CK_CPointerToObjCPointerCast:
340 case CK_BlockPointerToObjCPointerCast:
341 case CK_AnyPointerToBlockPointerCast:
342 case CK_ObjCObjectLValueCast:
343 case CK_ZeroToOCLEvent:
344 case CK_LValueBitCast: {
345 // Delegate to SValBuilder to process.
346 SVal V = state->getSVal(Ex, LCtx);
347 V = svalBuilder.evalCast(V, T, ExTy);
348 // Negate the result if we're treating the boolean as a signed i1
349 if (CastE->getCastKind() == CK_BooleanToSignedIntegral)
351 state = state->BindExpr(CastE, LCtx, V);
352 Bldr.generateNode(CastE, Pred, state);
355 case CK_IntegralCast: {
356 // Delegate to SValBuilder to process.
357 SVal V = state->getSVal(Ex, LCtx);
358 V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
359 state = state->BindExpr(CastE, LCtx, V);
360 Bldr.generateNode(CastE, Pred, state);
363 case CK_DerivedToBase:
364 case CK_UncheckedDerivedToBase: {
365 // For DerivedToBase cast, delegate to the store manager.
366 SVal val = state->getSVal(Ex, LCtx);
367 val = getStoreManager().evalDerivedToBase(val, CastE);
368 state = state->BindExpr(CastE, LCtx, val);
369 Bldr.generateNode(CastE, Pred, state);
372 // Handle C++ dyn_cast.
374 SVal val = state->getSVal(Ex, LCtx);
376 // Compute the type of the result.
377 QualType resultType = CastE->getType();
378 if (CastE->isGLValue())
379 resultType = getContext().getPointerType(resultType);
383 // Check if the value being cast evaluates to 0.
384 if (val.isZeroConstant())
386 // Else, evaluate the cast.
388 val = getStoreManager().evalDynamicCast(val, T, Failed);
391 if (T->isReferenceType()) {
392 // A bad_cast exception is thrown if input value is a reference.
393 // Currently, we model this, by generating a sink.
394 Bldr.generateSink(CastE, Pred, state);
397 // If the cast fails on a pointer, bind to 0.
398 state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
401 // If we don't know if the cast succeeded, conjure a new symbol.
402 if (val.isUnknown()) {
403 DefinedOrUnknownSVal NewSym =
404 svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
405 currBldrCtx->blockCount());
406 state = state->BindExpr(CastE, LCtx, NewSym);
408 // Else, bind to the derived region value.
409 state = state->BindExpr(CastE, LCtx, val);
411 Bldr.generateNode(CastE, Pred, state);
414 case CK_NullToMemberPointer: {
415 // FIXME: For now, member pointers are represented by void *.
416 SVal V = svalBuilder.makeNull();
417 state = state->BindExpr(CastE, LCtx, V);
418 Bldr.generateNode(CastE, Pred, state);
421 // Various C++ casts that are not handled yet.
423 case CK_BaseToDerived:
424 case CK_BaseToDerivedMemberPointer:
425 case CK_DerivedToBaseMemberPointer:
426 case CK_ReinterpretMemberPointer:
427 case CK_VectorSplat: {
428 // Recover some path-sensitivty by conjuring a new value.
429 QualType resultType = CastE->getType();
430 if (CastE->isGLValue())
431 resultType = getContext().getPointerType(resultType);
432 SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx,
434 currBldrCtx->blockCount());
435 state = state->BindExpr(CastE, LCtx, result);
436 Bldr.generateNode(CastE, Pred, state);
443 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
445 ExplodedNodeSet &Dst) {
446 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
448 ProgramStateRef State = Pred->getState();
449 const LocationContext *LCtx = Pred->getLocationContext();
451 const Expr *Init = CL->getInitializer();
452 SVal V = State->getSVal(CL->getInitializer(), LCtx);
454 if (isa<CXXConstructExpr>(Init)) {
455 // No work needed. Just pass the value up to this expression.
457 assert(isa<InitListExpr>(Init));
458 Loc CLLoc = State->getLValue(CL, LCtx);
459 State = State->bindLoc(CLLoc, V);
461 // Compound literal expressions are a GNU extension in C++.
462 // Unlike in C, where CLs are lvalues, in C++ CLs are prvalues,
463 // and like temporary objects created by the functional notation T()
464 // CLs are destroyed at the end of the containing full-expression.
465 // HOWEVER, an rvalue of array type is not something the analyzer can
466 // reason about, since we expect all regions to be wrapped in Locs.
467 // So we treat array CLs as lvalues as well, knowing that they will decay
468 // to pointers as soon as they are used.
469 if (CL->isGLValue() || CL->getType()->isArrayType())
473 B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
476 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
477 ExplodedNodeSet &Dst) {
478 // Assumption: The CFG has one DeclStmt per Decl.
479 const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
482 //TODO:AZ: remove explicit insertion after refactoring is done.
487 // FIXME: all pre/post visits should eventually be handled by ::Visit().
488 ExplodedNodeSet dstPreVisit;
489 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
491 ExplodedNodeSet dstEvaluated;
492 StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
493 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
495 ExplodedNode *N = *I;
496 ProgramStateRef state = N->getState();
497 const LocationContext *LC = N->getLocationContext();
499 // Decls without InitExpr are not initialized explicitly.
500 if (const Expr *InitEx = VD->getInit()) {
502 // Note in the state that the initialization has occurred.
503 ExplodedNode *UpdatedN = N;
504 SVal InitVal = state->getSVal(InitEx, LC);
506 assert(DS->isSingleDecl());
507 if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) {
508 assert(InitEx->IgnoreImplicit() == CtorExpr);
510 // We constructed the object directly in the variable.
511 // No need to bind anything.
512 B.generateNode(DS, UpdatedN, state);
514 // We bound the temp obj region to the CXXConstructExpr. Now recover
515 // the lazy compound value when the variable is not a reference.
516 if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
517 !VD->getType()->isReferenceType()) {
518 if (Optional<loc::MemRegionVal> M =
519 InitVal.getAs<loc::MemRegionVal>()) {
520 InitVal = state->getSVal(M->getRegion());
521 assert(InitVal.getAs<nonloc::LazyCompoundVal>());
525 // Recover some path-sensitivity if a scalar value evaluated to
527 if (InitVal.isUnknown()) {
528 QualType Ty = InitEx->getType();
529 if (InitEx->isGLValue()) {
530 Ty = getContext().getPointerType(Ty);
533 InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
534 currBldrCtx->blockCount());
538 B.takeNodes(UpdatedN);
539 ExplodedNodeSet Dst2;
540 evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
545 B.generateNode(DS, N, state);
549 getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
552 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
553 ExplodedNodeSet &Dst) {
554 assert(B->getOpcode() == BO_LAnd ||
555 B->getOpcode() == BO_LOr);
557 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
558 ProgramStateRef state = Pred->getState();
560 ExplodedNode *N = Pred;
561 while (!N->getLocation().getAs<BlockEntrance>()) {
562 ProgramPoint P = N->getLocation();
563 assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
565 assert(N->pred_size() == 1);
566 N = *N->pred_begin();
568 assert(N->pred_size() == 1);
569 N = *N->pred_begin();
570 BlockEdge BE = N->getLocation().castAs<BlockEdge>();
573 // Determine the value of the expression by introspecting how we
574 // got this location in the CFG. This requires looking at the previous
575 // block we were in and what kind of control-flow transfer was involved.
576 const CFGBlock *SrcBlock = BE.getSrc();
577 // The only terminator (if there is one) that makes sense is a logical op.
578 CFGTerminator T = SrcBlock->getTerminator();
579 if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
581 assert(Term->isLogicalOp());
582 assert(SrcBlock->succ_size() == 2);
583 // Did we take the true or false branch?
584 unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
585 X = svalBuilder.makeIntVal(constant, B->getType());
588 // If there is no terminator, by construction the last statement
589 // in SrcBlock is the value of the enclosing expression.
590 // However, we still need to constrain that value to be 0 or 1.
591 assert(!SrcBlock->empty());
592 CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
593 const Expr *RHS = cast<Expr>(Elem.getStmt());
594 SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
596 if (RHSVal.isUndef()) {
599 DefinedOrUnknownSVal DefinedRHS = RHSVal.castAs<DefinedOrUnknownSVal>();
600 ProgramStateRef StTrue, StFalse;
601 std::tie(StTrue, StFalse) = N->getState()->assume(DefinedRHS);
604 // We can't constrain the value to 0 or 1.
605 // The best we can do is a cast.
606 X = getSValBuilder().evalCast(RHSVal, B->getType(), RHS->getType());
608 // The value is known to be true.
609 X = getSValBuilder().makeIntVal(1, B->getType());
612 // The value is known to be false.
613 assert(StFalse && "Infeasible path!");
614 X = getSValBuilder().makeIntVal(0, B->getType());
618 Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
621 void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
623 ExplodedNodeSet &Dst) {
624 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
626 ProgramStateRef state = Pred->getState();
627 const LocationContext *LCtx = Pred->getLocationContext();
628 QualType T = getContext().getCanonicalType(IE->getType());
629 unsigned NumInitElements = IE->getNumInits();
631 if (!IE->isGLValue() &&
632 (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
633 T->isAnyComplexType())) {
634 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
636 // Handle base case where the initializer has no elements.
637 // e.g: static int* myArray[] = {};
638 if (NumInitElements == 0) {
639 SVal V = svalBuilder.makeCompoundVal(T, vals);
640 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
644 for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
645 ei = IE->rend(); it != ei; ++it) {
646 SVal V = state->getSVal(cast<Expr>(*it), LCtx);
647 vals = getBasicVals().consVals(V, vals);
650 B.generateNode(IE, Pred,
651 state->BindExpr(IE, LCtx,
652 svalBuilder.makeCompoundVal(T, vals)));
656 // Handle scalars: int{5} and int{} and GLvalues.
657 // Note, if the InitListExpr is a GLvalue, it means that there is an address
658 // representing it, so it must have a single init element.
659 assert(NumInitElements <= 1);
662 if (NumInitElements == 0)
663 V = getSValBuilder().makeZeroVal(T);
665 V = state->getSVal(IE->getInit(0), LCtx);
667 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
670 void ExprEngine::VisitGuardedExpr(const Expr *Ex,
674 ExplodedNodeSet &Dst) {
677 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
678 ProgramStateRef state = Pred->getState();
679 const LocationContext *LCtx = Pred->getLocationContext();
680 const CFGBlock *SrcBlock = nullptr;
682 // Find the predecessor block.
683 ProgramStateRef SrcState = state;
684 for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
685 ProgramPoint PP = N->getLocation();
686 if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
687 assert(N->pred_size() == 1);
690 SrcBlock = PP.castAs<BlockEdge>().getSrc();
691 SrcState = N->getState();
695 assert(SrcBlock && "missing function entry");
697 // Find the last expression in the predecessor block. That is the
698 // expression that is used for the value of the ternary expression.
699 bool hasValue = false;
702 for (CFGElement CE : llvm::reverse(*SrcBlock)) {
703 if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
704 const Expr *ValEx = cast<Expr>(CS->getStmt());
705 ValEx = ValEx->IgnoreParens();
707 // For GNU extension '?:' operator, the left hand side will be an
708 // OpaqueValueExpr, so get the underlying expression.
709 if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
710 L = OpaqueEx->getSourceExpr();
712 // If the last expression in the predecessor block matches true or false
713 // subexpression, get its the value.
714 if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
716 V = SrcState->getSVal(ValEx, LCtx);
723 V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
724 currBldrCtx->blockCount());
726 // Generate a new node with the binding from the appropriate path.
727 B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
731 VisitOffsetOfExpr(const OffsetOfExpr *OOE,
732 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
733 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
735 if (OOE->EvaluateAsInt(IV, getContext())) {
736 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
737 assert(OOE->getType()->isBuiltinType());
738 assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
739 assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
740 SVal X = svalBuilder.makeIntVal(IV);
741 B.generateNode(OOE, Pred,
742 Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
745 // FIXME: Handle the case where __builtin_offsetof is not a constant.
750 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
752 ExplodedNodeSet &Dst) {
753 // FIXME: Prechecks eventually go in ::Visit().
754 ExplodedNodeSet CheckedSet;
755 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
757 ExplodedNodeSet EvalSet;
758 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
760 QualType T = Ex->getTypeOfArgument();
762 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
764 if (Ex->getKind() == UETT_SizeOf) {
765 if (!T->isIncompleteType() && !T->isConstantSizeType()) {
766 assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
768 // FIXME: Add support for VLA type arguments and VLA expressions.
769 // When that happens, we should probably refactor VLASizeChecker's code.
771 } else if (T->getAs<ObjCObjectType>()) {
772 // Some code tries to take the sizeof an ObjCObjectType, relying that
773 // the compiler has laid out its representation. Just report Unknown
779 APSInt Value = Ex->EvaluateKnownConstInt(getContext());
780 CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
782 ProgramStateRef state = (*I)->getState();
783 state = state->BindExpr(Ex, (*I)->getLocationContext(),
784 svalBuilder.makeIntVal(amt.getQuantity(),
786 Bldr.generateNode(Ex, *I, state);
789 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
792 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
794 ExplodedNodeSet &Dst) {
795 // FIXME: Prechecks eventually go in ::Visit().
796 ExplodedNodeSet CheckedSet;
797 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
799 ExplodedNodeSet EvalSet;
800 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
802 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
804 switch (U->getOpcode()) {
808 VisitIncrementDecrementOperator(U, *I, Tmp);
813 const Expr *Ex = U->getSubExpr()->IgnoreParens();
815 // FIXME: We don't have complex SValues yet.
816 if (Ex->getType()->isAnyComplexType()) {
817 // Just report "Unknown."
821 // For all other types, UO_Real is an identity operation.
822 assert (U->getType() == Ex->getType());
823 ProgramStateRef state = (*I)->getState();
824 const LocationContext *LCtx = (*I)->getLocationContext();
825 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
826 state->getSVal(Ex, LCtx)));
831 const Expr *Ex = U->getSubExpr()->IgnoreParens();
832 // FIXME: We don't have complex SValues yet.
833 if (Ex->getType()->isAnyComplexType()) {
834 // Just report "Unknown."
837 // For all other types, UO_Imag returns 0.
838 ProgramStateRef state = (*I)->getState();
839 const LocationContext *LCtx = (*I)->getLocationContext();
840 SVal X = svalBuilder.makeZeroVal(Ex->getType());
841 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
846 assert(!U->isGLValue());
851 // FIXME: We can probably just have some magic in Environment::getSVal()
852 // that propagates values, instead of creating a new node here.
854 // Unary "+" is a no-op, similar to a parentheses. We still have places
855 // where it may be a block-level expression, so we need to
856 // generate an extra node that just propagates the value of the
858 const Expr *Ex = U->getSubExpr()->IgnoreParens();
859 ProgramStateRef state = (*I)->getState();
860 const LocationContext *LCtx = (*I)->getLocationContext();
861 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
862 state->getSVal(Ex, LCtx)));
869 assert (!U->isGLValue());
870 const Expr *Ex = U->getSubExpr()->IgnoreParens();
871 ProgramStateRef state = (*I)->getState();
872 const LocationContext *LCtx = (*I)->getLocationContext();
874 // Get the value of the subexpression.
875 SVal V = state->getSVal(Ex, LCtx);
877 if (V.isUnknownOrUndef()) {
878 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
882 switch (U->getOpcode()) {
884 llvm_unreachable("Invalid Opcode.");
886 // FIXME: Do we need to handle promotions?
887 state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
890 // FIXME: Do we need to handle promotions?
891 state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
894 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
896 // Note: technically we do "E == 0", but this is the same in the
897 // transfer functions as "0 == E".
899 if (Optional<Loc> LV = V.getAs<Loc>()) {
900 Loc X = svalBuilder.makeNull();
901 Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
903 else if (Ex->getType()->isFloatingType()) {
904 // FIXME: handle floating point types.
905 Result = UnknownVal();
907 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
908 Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
912 state = state->BindExpr(U, LCtx, Result);
915 Bldr.generateNode(U, *I, state);
921 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
924 void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
926 ExplodedNodeSet &Dst) {
927 // Handle ++ and -- (both pre- and post-increment).
928 assert (U->isIncrementDecrementOp());
929 const Expr *Ex = U->getSubExpr()->IgnoreParens();
931 const LocationContext *LCtx = Pred->getLocationContext();
932 ProgramStateRef state = Pred->getState();
933 SVal loc = state->getSVal(Ex, LCtx);
937 evalLoad(Tmp, U, Ex, Pred, state, loc);
939 ExplodedNodeSet Dst2;
940 StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
941 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
943 state = (*I)->getState();
944 assert(LCtx == (*I)->getLocationContext());
945 SVal V2_untested = state->getSVal(Ex, LCtx);
947 // Propagate unknown and undefined values.
948 if (V2_untested.isUnknownOrUndef()) {
949 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
952 DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
954 // Handle all other values.
955 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
957 // If the UnaryOperator has non-location type, use its type to create the
958 // constant value. If the UnaryOperator has location type, create the
959 // constant with int type and pointer width.
962 if (U->getType()->isAnyPointerType())
963 RHS = svalBuilder.makeArrayIndex(1);
964 else if (U->getType()->isIntegralOrEnumerationType())
965 RHS = svalBuilder.makeIntVal(1, U->getType());
969 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
971 // Conjure a new symbol if necessary to recover precision.
972 if (Result.isUnknown()){
973 DefinedOrUnknownSVal SymVal =
974 svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
975 currBldrCtx->blockCount());
978 // If the value is a location, ++/-- should always preserve
979 // non-nullness. Check if the original value was non-null, and if so
980 // propagate that constraint.
981 if (Loc::isLocType(U->getType())) {
982 DefinedOrUnknownSVal Constraint =
983 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
985 if (!state->assume(Constraint, true)) {
986 // It isn't feasible for the original value to be null.
987 // Propagate this constraint.
988 Constraint = svalBuilder.evalEQ(state, SymVal,
989 svalBuilder.makeZeroVal(U->getType()));
992 state = state->assume(Constraint, false);
998 // Since the lvalue-to-rvalue conversion is explicit in the AST,
999 // we bind an l-value if the operator is prefix and an lvalue (in C++).
1001 state = state->BindExpr(U, LCtx, loc);
1003 state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
1005 // Perform the store.
1007 ExplodedNodeSet Dst3;
1008 evalStore(Dst3, U, U, *I, state, loc, Result);
1009 Bldr.addNodes(Dst3);