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/StaticAnalyzer/Core/CheckerManager.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
16 
17 using namespace clang;
18 using namespace ento;
19 using llvm::APSInt;
20 
21 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
22                                      ExplodedNode *Pred,
23                                      ExplodedNodeSet &Dst) {
24 
25   Expr *LHS = B->getLHS()->IgnoreParens();
26   Expr *RHS = B->getRHS()->IgnoreParens();
27 
28   // FIXME: Prechecks eventually go in ::Visit().
29   ExplodedNodeSet CheckedSet;
30   ExplodedNodeSet Tmp2;
31   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
32 
33   // With both the LHS and RHS evaluated, process the operation itself.
34   for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
35          it != ei; ++it) {
36 
37     ProgramStateRef state = (*it)->getState();
38     const LocationContext *LCtx = (*it)->getLocationContext();
39     SVal LeftV = state->getSVal(LHS, LCtx);
40     SVal RightV = state->getSVal(RHS, LCtx);
41 
42     BinaryOperator::Opcode Op = B->getOpcode();
43 
44     if (Op == BO_Assign) {
45       // EXPERIMENTAL: "Conjured" symbols.
46       // FIXME: Handle structs.
47       if (RightV.isUnknown()) {
48         unsigned Count = currentBuilderContext->getCurrentBlockCount();
49         RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count);
50       }
51       // Simulate the effects of a "store":  bind the value of the RHS
52       // to the L-Value represented by the LHS.
53       SVal ExprVal = B->isLValue() ? LeftV : RightV;
54       evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
55                 LeftV, RightV);
56       continue;
57     }
58 
59     if (!B->isAssignmentOp()) {
60       StmtNodeBuilder Bldr(*it, Tmp2, *currentBuilderContext);
61       // Process non-assignments except commas or short-circuited
62       // logical expressions (LAnd and LOr).
63       SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
64       if (Result.isUnknown()) {
65         Bldr.generateNode(B, *it, state);
66         continue;
67       }
68 
69       state = state->BindExpr(B, LCtx, Result);
70       Bldr.generateNode(B, *it, state);
71       continue;
72     }
73 
74     assert (B->isCompoundAssignmentOp());
75 
76     switch (Op) {
77       default:
78         llvm_unreachable("Invalid opcode for compound assignment.");
79       case BO_MulAssign: Op = BO_Mul; break;
80       case BO_DivAssign: Op = BO_Div; break;
81       case BO_RemAssign: Op = BO_Rem; break;
82       case BO_AddAssign: Op = BO_Add; break;
83       case BO_SubAssign: Op = BO_Sub; break;
84       case BO_ShlAssign: Op = BO_Shl; break;
85       case BO_ShrAssign: Op = BO_Shr; break;
86       case BO_AndAssign: Op = BO_And; break;
87       case BO_XorAssign: Op = BO_Xor; break;
88       case BO_OrAssign:  Op = BO_Or;  break;
89     }
90 
91     // Perform a load (the LHS).  This performs the checks for
92     // null dereferences, and so on.
93     ExplodedNodeSet Tmp;
94     SVal location = LeftV;
95     evalLoad(Tmp, LHS, *it, state, location);
96 
97     for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
98          ++I) {
99 
100       state = (*I)->getState();
101       const LocationContext *LCtx = (*I)->getLocationContext();
102       SVal V = state->getSVal(LHS, LCtx);
103 
104       // Get the computation type.
105       QualType CTy =
106         cast<CompoundAssignOperator>(B)->getComputationResultType();
107       CTy = getContext().getCanonicalType(CTy);
108 
109       QualType CLHSTy =
110         cast<CompoundAssignOperator>(B)->getComputationLHSType();
111       CLHSTy = getContext().getCanonicalType(CLHSTy);
112 
113       QualType LTy = getContext().getCanonicalType(LHS->getType());
114 
115       // Promote LHS.
116       V = svalBuilder.evalCast(V, CLHSTy, LTy);
117 
118       // Compute the result of the operation.
119       SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
120                                          B->getType(), CTy);
121 
122       // EXPERIMENTAL: "Conjured" symbols.
123       // FIXME: Handle structs.
124 
125       SVal LHSVal;
126 
127       if (Result.isUnknown()) {
128 
129         unsigned Count = currentBuilderContext->getCurrentBlockCount();
130 
131         // The symbolic value is actually for the type of the left-hand side
132         // expression, not the computation type, as this is the value the
133         // LValue on the LHS will bind to.
134         LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy,
135                                                   Count);
136 
137         // However, we need to convert the symbol to the computation type.
138         Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
139       }
140       else {
141         // The left-hand side may bind to a different value then the
142         // computation type.
143         LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
144       }
145 
146       // In C++, assignment and compound assignment operators return an
147       // lvalue.
148       if (B->isLValue())
149         state = state->BindExpr(B, LCtx, location);
150       else
151         state = state->BindExpr(B, LCtx, Result);
152 
153       evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
154     }
155   }
156 
157   // FIXME: postvisits eventually go in ::Visit()
158   getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
159 }
160 
161 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
162                                 ExplodedNodeSet &Dst) {
163 
164   CanQualType T = getContext().getCanonicalType(BE->getType());
165   SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
166                                        Pred->getLocationContext());
167 
168   ExplodedNodeSet Tmp;
169   StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext);
170   Bldr.generateNode(BE, Pred,
171                     Pred->getState()->BindExpr(BE, Pred->getLocationContext(),
172                                                V),
173                     false, 0,
174                     ProgramPoint::PostLValueKind);
175 
176   // FIXME: Move all post/pre visits to ::Visit().
177   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
178 }
179 
180 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
181                            ExplodedNode *Pred, ExplodedNodeSet &Dst) {
182 
183   ExplodedNodeSet dstPreStmt;
184   getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
185 
186   if (CastE->getCastKind() == CK_LValueToRValue) {
187     for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
188          I!=E; ++I) {
189       ExplodedNode *subExprNode = *I;
190       ProgramStateRef state = subExprNode->getState();
191       const LocationContext *LCtx = subExprNode->getLocationContext();
192       evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
193     }
194     return;
195   }
196 
197   // All other casts.
198   QualType T = CastE->getType();
199   QualType ExTy = Ex->getType();
200 
201   if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
202     T = ExCast->getTypeAsWritten();
203 
204   StmtNodeBuilder Bldr(dstPreStmt, Dst, *currentBuilderContext);
205   for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
206        I != E; ++I) {
207 
208     Pred = *I;
209 
210     switch (CastE->getCastKind()) {
211       case CK_LValueToRValue:
212         llvm_unreachable("LValueToRValue casts handled earlier.");
213       case CK_ToVoid:
214         continue;
215         // The analyzer doesn't do anything special with these casts,
216         // since it understands retain/release semantics already.
217       case CK_ARCProduceObject:
218       case CK_ARCConsumeObject:
219       case CK_ARCReclaimReturnedObject:
220       case CK_ARCExtendBlockObject: // Fall-through.
221         // The analyser can ignore atomic casts for now, although some future
222         // checkers may want to make certain that you're not modifying the same
223         // value through atomic and nonatomic pointers.
224       case CK_AtomicToNonAtomic:
225       case CK_NonAtomicToAtomic:
226         // True no-ops.
227       case CK_NoOp:
228       case CK_FunctionToPointerDecay: {
229         // Copy the SVal of Ex to CastE.
230         ProgramStateRef state = Pred->getState();
231         const LocationContext *LCtx = Pred->getLocationContext();
232         SVal V = state->getSVal(Ex, LCtx);
233         state = state->BindExpr(CastE, LCtx, V);
234         Bldr.generateNode(CastE, Pred, state);
235         continue;
236       }
237       case CK_Dependent:
238       case CK_ArrayToPointerDecay:
239       case CK_BitCast:
240       case CK_LValueBitCast:
241       case CK_IntegralCast:
242       case CK_NullToPointer:
243       case CK_IntegralToPointer:
244       case CK_PointerToIntegral:
245       case CK_PointerToBoolean:
246       case CK_IntegralToBoolean:
247       case CK_IntegralToFloating:
248       case CK_FloatingToIntegral:
249       case CK_FloatingToBoolean:
250       case CK_FloatingCast:
251       case CK_FloatingRealToComplex:
252       case CK_FloatingComplexToReal:
253       case CK_FloatingComplexToBoolean:
254       case CK_FloatingComplexCast:
255       case CK_FloatingComplexToIntegralComplex:
256       case CK_IntegralRealToComplex:
257       case CK_IntegralComplexToReal:
258       case CK_IntegralComplexToBoolean:
259       case CK_IntegralComplexCast:
260       case CK_IntegralComplexToFloatingComplex:
261       case CK_CPointerToObjCPointerCast:
262       case CK_BlockPointerToObjCPointerCast:
263       case CK_AnyPointerToBlockPointerCast:
264       case CK_ObjCObjectLValueCast: {
265         // Delegate to SValBuilder to process.
266         ProgramStateRef state = Pred->getState();
267         const LocationContext *LCtx = Pred->getLocationContext();
268         SVal V = state->getSVal(Ex, LCtx);
269         V = svalBuilder.evalCast(V, T, ExTy);
270         state = state->BindExpr(CastE, LCtx, V);
271         Bldr.generateNode(CastE, Pred, state);
272         continue;
273       }
274       case CK_DerivedToBase:
275       case CK_UncheckedDerivedToBase: {
276         // For DerivedToBase cast, delegate to the store manager.
277         ProgramStateRef state = Pred->getState();
278         const LocationContext *LCtx = Pred->getLocationContext();
279         SVal val = state->getSVal(Ex, LCtx);
280         val = getStoreManager().evalDerivedToBase(val, T);
281         state = state->BindExpr(CastE, LCtx, val);
282         Bldr.generateNode(CastE, Pred, state);
283         continue;
284       }
285         // Various C++ casts that are not handled yet.
286       case CK_Dynamic:
287       case CK_ToUnion:
288       case CK_BaseToDerived:
289       case CK_NullToMemberPointer:
290       case CK_BaseToDerivedMemberPointer:
291       case CK_DerivedToBaseMemberPointer:
292       case CK_UserDefinedConversion:
293       case CK_ConstructorConversion:
294       case CK_VectorSplat:
295       case CK_MemberPointerToBoolean: {
296         // Recover some path-sensitivty by conjuring a new value.
297         QualType resultType = CastE->getType();
298         if (CastE->isLValue())
299           resultType = getContext().getPointerType(resultType);
300 
301         SVal result =
302         svalBuilder.getConjuredSymbolVal(NULL, CastE, resultType,
303                                currentBuilderContext->getCurrentBlockCount());
304 
305         const LocationContext *LCtx = Pred->getLocationContext();
306         ProgramStateRef state = Pred->getState()->BindExpr(CastE, LCtx,
307                                                                result);
308         Bldr.generateNode(CastE, Pred, state);
309         continue;
310       }
311     }
312   }
313 }
314 
315 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
316                                           ExplodedNode *Pred,
317                                           ExplodedNodeSet &Dst) {
318   StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
319 
320   const InitListExpr *ILE
321     = cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
322 
323   ProgramStateRef state = Pred->getState();
324   SVal ILV = state->getSVal(ILE, Pred->getLocationContext());
325   const LocationContext *LC = Pred->getLocationContext();
326   state = state->bindCompoundLiteral(CL, LC, ILV);
327 
328   if (CL->isLValue())
329     B.generateNode(CL, Pred, state->BindExpr(CL, LC, state->getLValue(CL, LC)));
330   else
331     B.generateNode(CL, Pred, state->BindExpr(CL, LC, ILV));
332 }
333 
334 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
335                                ExplodedNodeSet &Dst) {
336 
337   // FIXME: static variables may have an initializer, but the second
338   //  time a function is called those values may not be current.
339   //  This may need to be reflected in the CFG.
340 
341   // Assumption: The CFG has one DeclStmt per Decl.
342   const Decl *D = *DS->decl_begin();
343 
344   if (!D || !isa<VarDecl>(D)) {
345     //TODO:AZ: remove explicit insertion after refactoring is done.
346     Dst.insert(Pred);
347     return;
348   }
349 
350   // FIXME: all pre/post visits should eventually be handled by ::Visit().
351   ExplodedNodeSet dstPreVisit;
352   getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
353 
354   StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext);
355   const VarDecl *VD = dyn_cast<VarDecl>(D);
356   for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
357        I!=E; ++I) {
358     ExplodedNode *N = *I;
359     ProgramStateRef state = N->getState();
360 
361     // Decls without InitExpr are not initialized explicitly.
362     const LocationContext *LC = N->getLocationContext();
363 
364     if (const Expr *InitEx = VD->getInit()) {
365       SVal InitVal = state->getSVal(InitEx, Pred->getLocationContext());
366 
367       // We bound the temp obj region to the CXXConstructExpr. Now recover
368       // the lazy compound value when the variable is not a reference.
369       if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() &&
370           !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){
371         InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion());
372         assert(isa<nonloc::LazyCompoundVal>(InitVal));
373       }
374 
375       // Recover some path-sensitivity if a scalar value evaluated to
376       // UnknownVal.
377       if (InitVal.isUnknown()) {
378         InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx,
379                                  currentBuilderContext->getCurrentBlockCount());
380       }
381       B.takeNodes(N);
382       ExplodedNodeSet Dst2;
383       evalBind(Dst2, DS, N, state->getLValue(VD, LC), InitVal, true);
384       B.addNodes(Dst2);
385     }
386     else {
387       B.generateNode(DS, N,state->bindDeclWithNoInit(state->getRegion(VD, LC)));
388     }
389   }
390 }
391 
392 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
393                                   ExplodedNodeSet &Dst) {
394   assert(B->getOpcode() == BO_LAnd ||
395          B->getOpcode() == BO_LOr);
396 
397   StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
398   ProgramStateRef state = Pred->getState();
399   const LocationContext *LCtx = Pred->getLocationContext();
400   SVal X = state->getSVal(B, LCtx);
401   assert(X.isUndef());
402 
403   const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData();
404   assert(Ex);
405 
406   if (Ex == B->getRHS()) {
407     X = state->getSVal(Ex, LCtx);
408 
409     // Handle undefined values.
410     if (X.isUndef()) {
411       Bldr.generateNode(B, Pred, state->BindExpr(B, LCtx, X));
412       return;
413     }
414 
415     DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X);
416 
417     // We took the RHS.  Because the value of the '&&' or '||' expression must
418     // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0
419     // or 1.  Alternatively, we could take a lazy approach, and calculate this
420     // value later when necessary.  We don't have the machinery in place for
421     // this right now, and since most logical expressions are used for branches,
422     // the payoff is not likely to be large.  Instead, we do eager evaluation.
423     if (ProgramStateRef newState = state->assume(XD, true))
424       Bldr.generateNode(B, Pred,
425                newState->BindExpr(B, LCtx,
426                                   svalBuilder.makeIntVal(1U, B->getType())));
427 
428     if (ProgramStateRef newState = state->assume(XD, false))
429       Bldr.generateNode(B, Pred,
430                newState->BindExpr(B, LCtx,
431                                   svalBuilder.makeIntVal(0U, B->getType())));
432   }
433   else {
434     // We took the LHS expression.  Depending on whether we are '&&' or
435     // '||' we know what the value of the expression is via properties of
436     // the short-circuiting.
437     X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U,
438                                B->getType());
439     Bldr.generateNode(B, Pred, state->BindExpr(B, LCtx, X));
440   }
441 }
442 
443 void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
444                                    ExplodedNode *Pred,
445                                    ExplodedNodeSet &Dst) {
446   StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
447 
448   ProgramStateRef state = Pred->getState();
449   const LocationContext *LCtx = Pred->getLocationContext();
450   QualType T = getContext().getCanonicalType(IE->getType());
451   unsigned NumInitElements = IE->getNumInits();
452 
453   if (T->isArrayType() || T->isRecordType() || T->isVectorType()) {
454     llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
455 
456     // Handle base case where the initializer has no elements.
457     // e.g: static int* myArray[] = {};
458     if (NumInitElements == 0) {
459       SVal V = svalBuilder.makeCompoundVal(T, vals);
460       B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
461       return;
462     }
463 
464     for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
465          ei = IE->rend(); it != ei; ++it) {
466       vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it), LCtx),
467                                      vals);
468     }
469 
470     B.generateNode(IE, Pred,
471                    state->BindExpr(IE, LCtx,
472                                    svalBuilder.makeCompoundVal(T, vals)));
473     return;
474   }
475 
476   if (Loc::isLocType(T) || T->isIntegerType()) {
477     assert(IE->getNumInits() == 1);
478     const Expr *initEx = IE->getInit(0);
479     B.generateNode(IE, Pred, state->BindExpr(IE, LCtx,
480                                              state->getSVal(initEx, LCtx)));
481     return;
482   }
483 
484   llvm_unreachable("unprocessed InitListExpr type");
485 }
486 
487 void ExprEngine::VisitGuardedExpr(const Expr *Ex,
488                                   const Expr *L,
489                                   const Expr *R,
490                                   ExplodedNode *Pred,
491                                   ExplodedNodeSet &Dst) {
492   StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
493 
494   ProgramStateRef state = Pred->getState();
495   const LocationContext *LCtx = Pred->getLocationContext();
496   SVal X = state->getSVal(Ex, LCtx);
497   assert (X.isUndef());
498   const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData();
499   assert(SE);
500   X = state->getSVal(SE, LCtx);
501 
502   // Make sure that we invalidate the previous binding.
503   B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, X, true));
504 }
505 
506 void ExprEngine::
507 VisitOffsetOfExpr(const OffsetOfExpr *OOE,
508                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
509   StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
510   APSInt IV;
511   if (OOE->EvaluateAsInt(IV, getContext())) {
512     assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
513     assert(OOE->getType()->isIntegerType());
514     assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType());
515     SVal X = svalBuilder.makeIntVal(IV);
516     B.generateNode(OOE, Pred,
517                    Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
518                                               X));
519   }
520   // FIXME: Handle the case where __builtin_offsetof is not a constant.
521 }
522 
523 
524 void ExprEngine::
525 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
526                               ExplodedNode *Pred,
527                               ExplodedNodeSet &Dst) {
528   StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
529 
530   QualType T = Ex->getTypeOfArgument();
531 
532   if (Ex->getKind() == UETT_SizeOf) {
533     if (!T->isIncompleteType() && !T->isConstantSizeType()) {
534       assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
535 
536       // FIXME: Add support for VLA type arguments and VLA expressions.
537       // When that happens, we should probably refactor VLASizeChecker's code.
538       return;
539     }
540     else if (T->getAs<ObjCObjectType>()) {
541       // Some code tries to take the sizeof an ObjCObjectType, relying that
542       // the compiler has laid out its representation.  Just report Unknown
543       // for these.
544       return;
545     }
546   }
547 
548   APSInt Value = Ex->EvaluateKnownConstInt(getContext());
549   CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
550 
551   ProgramStateRef state = Pred->getState();
552   state = state->BindExpr(Ex, Pred->getLocationContext(),
553                           svalBuilder.makeIntVal(amt.getQuantity(),
554                                                      Ex->getType()));
555   Bldr.generateNode(Ex, Pred, state);
556 }
557 
558 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
559                                     ExplodedNode *Pred,
560                                     ExplodedNodeSet &Dst) {
561   StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
562   switch (U->getOpcode()) {
563     default: {
564       Bldr.takeNodes(Pred);
565       ExplodedNodeSet Tmp;
566       VisitIncrementDecrementOperator(U, Pred, Tmp);
567       Bldr.addNodes(Tmp);
568     }
569       break;
570     case UO_Real: {
571       const Expr *Ex = U->getSubExpr()->IgnoreParens();
572       ExplodedNodeSet Tmp;
573       Visit(Ex, Pred, Tmp);
574 
575       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
576 
577         // FIXME: We don't have complex SValues yet.
578         if (Ex->getType()->isAnyComplexType()) {
579           // Just report "Unknown."
580           continue;
581         }
582 
583         // For all other types, UO_Real is an identity operation.
584         assert (U->getType() == Ex->getType());
585         ProgramStateRef state = (*I)->getState();
586         const LocationContext *LCtx = (*I)->getLocationContext();
587         Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
588                                                  state->getSVal(Ex, LCtx)));
589       }
590 
591       break;
592     }
593 
594     case UO_Imag: {
595 
596       const Expr *Ex = U->getSubExpr()->IgnoreParens();
597       ExplodedNodeSet Tmp;
598       Visit(Ex, Pred, Tmp);
599 
600       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
601         // FIXME: We don't have complex SValues yet.
602         if (Ex->getType()->isAnyComplexType()) {
603           // Just report "Unknown."
604           continue;
605         }
606 
607         // For all other types, UO_Imag returns 0.
608         ProgramStateRef state = (*I)->getState();
609         const LocationContext *LCtx = (*I)->getLocationContext();
610         SVal X = svalBuilder.makeZeroVal(Ex->getType());
611         Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
612       }
613 
614       break;
615     }
616 
617     case UO_Plus:
618       assert(!U->isLValue());
619       // FALL-THROUGH.
620     case UO_Deref:
621     case UO_AddrOf:
622     case UO_Extension: {
623 
624       // Unary "+" is a no-op, similar to a parentheses.  We still have places
625       // where it may be a block-level expression, so we need to
626       // generate an extra node that just propagates the value of the
627       // subexpression.
628 
629       const Expr *Ex = U->getSubExpr()->IgnoreParens();
630       ExplodedNodeSet Tmp;
631       Visit(Ex, Pred, Tmp);
632 
633       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
634         ProgramStateRef state = (*I)->getState();
635         const LocationContext *LCtx = (*I)->getLocationContext();
636         Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
637                                                  state->getSVal(Ex, LCtx)));
638       }
639 
640       break;
641     }
642 
643     case UO_LNot:
644     case UO_Minus:
645     case UO_Not: {
646       assert (!U->isLValue());
647       const Expr *Ex = U->getSubExpr()->IgnoreParens();
648       ExplodedNodeSet Tmp;
649       Visit(Ex, Pred, Tmp);
650 
651       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
652         ProgramStateRef state = (*I)->getState();
653         const LocationContext *LCtx = (*I)->getLocationContext();
654 
655         // Get the value of the subexpression.
656         SVal V = state->getSVal(Ex, LCtx);
657 
658         if (V.isUnknownOrUndef()) {
659           Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
660           continue;
661         }
662 
663         switch (U->getOpcode()) {
664           default:
665             llvm_unreachable("Invalid Opcode.");
666 
667           case UO_Not:
668             // FIXME: Do we need to handle promotions?
669             state = state->BindExpr(U, LCtx, evalComplement(cast<NonLoc>(V)));
670             break;
671 
672           case UO_Minus:
673             // FIXME: Do we need to handle promotions?
674             state = state->BindExpr(U, LCtx, evalMinus(cast<NonLoc>(V)));
675             break;
676 
677           case UO_LNot:
678 
679             // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
680             //
681             //  Note: technically we do "E == 0", but this is the same in the
682             //    transfer functions as "0 == E".
683             SVal Result;
684 
685             if (isa<Loc>(V)) {
686               Loc X = svalBuilder.makeNull();
687               Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X,
688                                  U->getType());
689             }
690             else {
691               nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
692               Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
693                                  U->getType());
694             }
695 
696             state = state->BindExpr(U, LCtx, Result);
697 
698             break;
699         }
700         Bldr.generateNode(U, *I, state);
701       }
702       break;
703     }
704   }
705 
706 }
707 
708 void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
709                                                  ExplodedNode *Pred,
710                                                  ExplodedNodeSet &Dst) {
711   // Handle ++ and -- (both pre- and post-increment).
712   assert (U->isIncrementDecrementOp());
713   ExplodedNodeSet Tmp;
714   const Expr *Ex = U->getSubExpr()->IgnoreParens();
715   Visit(Ex, Pred, Tmp);
716 
717   for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
718     const LocationContext *LCtx = (*I)->getLocationContext();
719     ProgramStateRef state = (*I)->getState();
720     SVal loc = state->getSVal(Ex, LCtx);
721 
722     // Perform a load.
723     ExplodedNodeSet Tmp2;
724     evalLoad(Tmp2, Ex, *I, state, loc);
725 
726     ExplodedNodeSet Dst2;
727     StmtNodeBuilder Bldr(Tmp2, Dst2, *currentBuilderContext);
728     for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) {
729 
730       state = (*I2)->getState();
731       assert(LCtx == (*I2)->getLocationContext());
732       SVal V2_untested = state->getSVal(Ex, LCtx);
733 
734       // Propagate unknown and undefined values.
735       if (V2_untested.isUnknownOrUndef()) {
736         Bldr.generateNode(U, *I2, state->BindExpr(U, LCtx, V2_untested));
737         continue;
738       }
739       DefinedSVal V2 = cast<DefinedSVal>(V2_untested);
740 
741       // Handle all other values.
742       BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add
743       : BO_Sub;
744 
745       // If the UnaryOperator has non-location type, use its type to create the
746       // constant value. If the UnaryOperator has location type, create the
747       // constant with int type and pointer width.
748       SVal RHS;
749 
750       if (U->getType()->isAnyPointerType())
751         RHS = svalBuilder.makeArrayIndex(1);
752       else
753         RHS = svalBuilder.makeIntVal(1, U->getType());
754 
755       SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
756 
757       // Conjure a new symbol if necessary to recover precision.
758       if (Result.isUnknown()){
759         DefinedOrUnknownSVal SymVal =
760         svalBuilder.getConjuredSymbolVal(NULL, Ex,
761                                  currentBuilderContext->getCurrentBlockCount());
762         Result = SymVal;
763 
764         // If the value is a location, ++/-- should always preserve
765         // non-nullness.  Check if the original value was non-null, and if so
766         // propagate that constraint.
767         if (Loc::isLocType(U->getType())) {
768           DefinedOrUnknownSVal Constraint =
769           svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
770 
771           if (!state->assume(Constraint, true)) {
772             // It isn't feasible for the original value to be null.
773             // Propagate this constraint.
774             Constraint = svalBuilder.evalEQ(state, SymVal,
775                                          svalBuilder.makeZeroVal(U->getType()));
776 
777 
778             state = state->assume(Constraint, false);
779             assert(state);
780           }
781         }
782       }
783 
784       // Since the lvalue-to-rvalue conversion is explicit in the AST,
785       // we bind an l-value if the operator is prefix and an lvalue (in C++).
786       if (U->isLValue())
787         state = state->BindExpr(U, LCtx, loc);
788       else
789         state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
790 
791       // Perform the store.
792       Bldr.takeNodes(*I2);
793       ExplodedNodeSet Dst4;
794       evalStore(Dst4, NULL, U, *I2, state, loc, Result);
795       Bldr.addNodes(Dst4);
796     }
797     Dst.insert(Dst2);
798   }
799 }
800