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