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