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()->isIntegerType() && RightV.isUnknown()) {
72           RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(),
73                                                 Count);
74         }
75         if (RightV.getAs<Loc>() &&
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       case CK_ZeroToOCLEvent: {
311         // Delegate to SValBuilder to process.
312         SVal V = state->getSVal(Ex, LCtx);
313         V = svalBuilder.evalCast(V, T, ExTy);
314         state = state->BindExpr(CastE, LCtx, V);
315         Bldr.generateNode(CastE, Pred, state);
316         continue;
317       }
318       case CK_DerivedToBase:
319       case CK_UncheckedDerivedToBase: {
320         // For DerivedToBase cast, delegate to the store manager.
321         SVal val = state->getSVal(Ex, LCtx);
322         val = getStoreManager().evalDerivedToBase(val, CastE);
323         state = state->BindExpr(CastE, LCtx, val);
324         Bldr.generateNode(CastE, Pred, state);
325         continue;
326       }
327       // Handle C++ dyn_cast.
328       case CK_Dynamic: {
329         SVal val = state->getSVal(Ex, LCtx);
330 
331         // Compute the type of the result.
332         QualType resultType = CastE->getType();
333         if (CastE->isGLValue())
334           resultType = getContext().getPointerType(resultType);
335 
336         bool Failed = false;
337 
338         // Check if the value being cast evaluates to 0.
339         if (val.isZeroConstant())
340           Failed = true;
341         // Else, evaluate the cast.
342         else
343           val = getStoreManager().evalDynamicCast(val, T, Failed);
344 
345         if (Failed) {
346           if (T->isReferenceType()) {
347             // A bad_cast exception is thrown if input value is a reference.
348             // Currently, we model this, by generating a sink.
349             Bldr.generateSink(CastE, Pred, state);
350             continue;
351           } else {
352             // If the cast fails on a pointer, bind to 0.
353             state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
354           }
355         } else {
356           // If we don't know if the cast succeeded, conjure a new symbol.
357           if (val.isUnknown()) {
358             DefinedOrUnknownSVal NewSym =
359               svalBuilder.conjureSymbolVal(0, CastE, LCtx, resultType,
360                                            currBldrCtx->blockCount());
361             state = state->BindExpr(CastE, LCtx, NewSym);
362           } else
363             // Else, bind to the derived region value.
364             state = state->BindExpr(CastE, LCtx, val);
365         }
366         Bldr.generateNode(CastE, Pred, state);
367         continue;
368       }
369       case CK_NullToMemberPointer: {
370         // FIXME: For now, member pointers are represented by void *.
371         SVal V = svalBuilder.makeIntValWithPtrWidth(0, true);
372         state = state->BindExpr(CastE, LCtx, V);
373         Bldr.generateNode(CastE, Pred, state);
374         continue;
375       }
376       // Various C++ casts that are not handled yet.
377       case CK_ToUnion:
378       case CK_BaseToDerived:
379       case CK_BaseToDerivedMemberPointer:
380       case CK_DerivedToBaseMemberPointer:
381       case CK_ReinterpretMemberPointer:
382       case CK_VectorSplat:
383       case CK_LValueBitCast: {
384         // Recover some path-sensitivty by conjuring a new value.
385         QualType resultType = CastE->getType();
386         if (CastE->isGLValue())
387           resultType = getContext().getPointerType(resultType);
388         SVal result = svalBuilder.conjureSymbolVal(0, CastE, LCtx,
389                                                    resultType,
390                                                    currBldrCtx->blockCount());
391         state = state->BindExpr(CastE, LCtx, result);
392         Bldr.generateNode(CastE, Pred, state);
393         continue;
394       }
395     }
396   }
397 }
398 
399 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
400                                           ExplodedNode *Pred,
401                                           ExplodedNodeSet &Dst) {
402   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
403 
404   const InitListExpr *ILE
405     = cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
406 
407   ProgramStateRef state = Pred->getState();
408   SVal ILV = state->getSVal(ILE, Pred->getLocationContext());
409   const LocationContext *LC = Pred->getLocationContext();
410   state = state->bindCompoundLiteral(CL, LC, ILV);
411 
412   // Compound literal expressions are a GNU extension in C++.
413   // Unlike in C, where CLs are lvalues, in C++ CLs are prvalues,
414   // and like temporary objects created by the functional notation T()
415   // CLs are destroyed at the end of the containing full-expression.
416   // HOWEVER, an rvalue of array type is not something the analyzer can
417   // reason about, since we expect all regions to be wrapped in Locs.
418   // So we treat array CLs as lvalues as well, knowing that they will decay
419   // to pointers as soon as they are used.
420   if (CL->isGLValue() || CL->getType()->isArrayType())
421     B.generateNode(CL, Pred, state->BindExpr(CL, LC, state->getLValue(CL, LC)));
422   else
423     B.generateNode(CL, Pred, state->BindExpr(CL, LC, ILV));
424 }
425 
426 /// The GDM component containing the set of global variables which have been
427 /// previously initialized with explicit initializers.
428 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
429                                  llvm::ImmutableSet<const VarDecl *> )
430 
431 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
432                                ExplodedNodeSet &Dst) {
433   // Assumption: The CFG has one DeclStmt per Decl.
434   const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
435 
436   if (!VD) {
437     //TODO:AZ: remove explicit insertion after refactoring is done.
438     Dst.insert(Pred);
439     return;
440   }
441 
442   // Check if a value has been previously initialized. There will be an entry in
443   // the set for variables with global storage which have been previously
444   // initialized.
445   if (VD->hasGlobalStorage())
446     if (Pred->getState()->contains<InitializedGlobalsSet>(VD)) {
447       Dst.insert(Pred);
448       return;
449     }
450 
451   // FIXME: all pre/post visits should eventually be handled by ::Visit().
452   ExplodedNodeSet dstPreVisit;
453   getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
454 
455   StmtNodeBuilder B(dstPreVisit, Dst, *currBldrCtx);
456   for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
457        I!=E; ++I) {
458     ExplodedNode *N = *I;
459     ProgramStateRef state = N->getState();
460     const LocationContext *LC = N->getLocationContext();
461 
462     // Decls without InitExpr are not initialized explicitly.
463     if (const Expr *InitEx = VD->getInit()) {
464 
465       // Note in the state that the initialization has occurred.
466       ExplodedNode *UpdatedN = N;
467       if (VD->hasGlobalStorage()) {
468         state = state->add<InitializedGlobalsSet>(VD);
469         UpdatedN = B.generateNode(DS, N, state);
470       }
471 
472       SVal InitVal = state->getSVal(InitEx, LC);
473 
474       if (isa<CXXConstructExpr>(InitEx->IgnoreImplicit())) {
475         // We constructed the object directly in the variable.
476         // No need to bind anything.
477         B.generateNode(DS, UpdatedN, state);
478       } else {
479         // We bound the temp obj region to the CXXConstructExpr. Now recover
480         // the lazy compound value when the variable is not a reference.
481         if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
482             !VD->getType()->isReferenceType()) {
483           if (Optional<loc::MemRegionVal> M =
484                   InitVal.getAs<loc::MemRegionVal>()) {
485             InitVal = state->getSVal(M->getRegion());
486             assert(InitVal.getAs<nonloc::LazyCompoundVal>());
487           }
488         }
489 
490         // Recover some path-sensitivity if a scalar value evaluated to
491         // UnknownVal.
492         if (InitVal.isUnknown()) {
493           QualType Ty = InitEx->getType();
494           if (InitEx->isGLValue()) {
495             Ty = getContext().getPointerType(Ty);
496           }
497 
498           InitVal = svalBuilder.conjureSymbolVal(0, InitEx, LC, Ty,
499                                                  currBldrCtx->blockCount());
500         }
501 
502 
503         B.takeNodes(UpdatedN);
504         ExplodedNodeSet Dst2;
505         evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
506         B.addNodes(Dst2);
507       }
508     }
509     else {
510       B.generateNode(DS, N, state);
511     }
512   }
513 }
514 
515 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
516                                   ExplodedNodeSet &Dst) {
517   assert(B->getOpcode() == BO_LAnd ||
518          B->getOpcode() == BO_LOr);
519 
520   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
521   ProgramStateRef state = Pred->getState();
522 
523   ExplodedNode *N = Pred;
524   while (!N->getLocation().getAs<BlockEntrance>()) {
525     ProgramPoint P = N->getLocation();
526     assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
527     (void) P;
528     assert(N->pred_size() == 1);
529     N = *N->pred_begin();
530   }
531   assert(N->pred_size() == 1);
532   N = *N->pred_begin();
533   BlockEdge BE = N->getLocation().castAs<BlockEdge>();
534   SVal X;
535 
536   // Determine the value of the expression by introspecting how we
537   // got this location in the CFG.  This requires looking at the previous
538   // block we were in and what kind of control-flow transfer was involved.
539   const CFGBlock *SrcBlock = BE.getSrc();
540   // The only terminator (if there is one) that makes sense is a logical op.
541   CFGTerminator T = SrcBlock->getTerminator();
542   if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
543     (void) Term;
544     assert(Term->isLogicalOp());
545     assert(SrcBlock->succ_size() == 2);
546     // Did we take the true or false branch?
547     unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
548     X = svalBuilder.makeIntVal(constant, B->getType());
549   }
550   else {
551     // If there is no terminator, by construction the last statement
552     // in SrcBlock is the value of the enclosing expression.
553     // However, we still need to constrain that value to be 0 or 1.
554     assert(!SrcBlock->empty());
555     CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
556     const Expr *RHS = cast<Expr>(Elem.getStmt());
557     SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
558 
559     if (RHSVal.isUndef()) {
560       X = RHSVal;
561     } else {
562       DefinedOrUnknownSVal DefinedRHS = RHSVal.castAs<DefinedOrUnknownSVal>();
563       ProgramStateRef StTrue, StFalse;
564       llvm::tie(StTrue, StFalse) = N->getState()->assume(DefinedRHS);
565       if (StTrue) {
566         if (StFalse) {
567           // We can't constrain the value to 0 or 1.
568           // The best we can do is a cast.
569           X = getSValBuilder().evalCast(RHSVal, B->getType(), RHS->getType());
570         } else {
571           // The value is known to be true.
572           X = getSValBuilder().makeIntVal(1, B->getType());
573         }
574       } else {
575         // The value is known to be false.
576         assert(StFalse && "Infeasible path!");
577         X = getSValBuilder().makeIntVal(0, B->getType());
578       }
579     }
580   }
581   Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
582 }
583 
584 void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
585                                    ExplodedNode *Pred,
586                                    ExplodedNodeSet &Dst) {
587   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
588 
589   ProgramStateRef state = Pred->getState();
590   const LocationContext *LCtx = Pred->getLocationContext();
591   QualType T = getContext().getCanonicalType(IE->getType());
592   unsigned NumInitElements = IE->getNumInits();
593 
594   if (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
595       T->isAnyComplexType()) {
596     llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
597 
598     // Handle base case where the initializer has no elements.
599     // e.g: static int* myArray[] = {};
600     if (NumInitElements == 0) {
601       SVal V = svalBuilder.makeCompoundVal(T, vals);
602       B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
603       return;
604     }
605 
606     for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
607          ei = IE->rend(); it != ei; ++it) {
608       SVal V = state->getSVal(cast<Expr>(*it), LCtx);
609       if (dyn_cast_or_null<CXXTempObjectRegion>(V.getAsRegion()))
610         V = UnknownVal();
611       vals = getBasicVals().consVals(V, vals);
612     }
613 
614     B.generateNode(IE, Pred,
615                    state->BindExpr(IE, LCtx,
616                                    svalBuilder.makeCompoundVal(T, vals)));
617     return;
618   }
619 
620   // Handle scalars: int{5} and int{}.
621   assert(NumInitElements <= 1);
622 
623   SVal V;
624   if (NumInitElements == 0)
625     V = getSValBuilder().makeZeroVal(T);
626   else
627     V = state->getSVal(IE->getInit(0), LCtx);
628 
629   B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
630 }
631 
632 void ExprEngine::VisitGuardedExpr(const Expr *Ex,
633                                   const Expr *L,
634                                   const Expr *R,
635                                   ExplodedNode *Pred,
636                                   ExplodedNodeSet &Dst) {
637   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
638   ProgramStateRef state = Pred->getState();
639   const LocationContext *LCtx = Pred->getLocationContext();
640   const CFGBlock *SrcBlock = 0;
641 
642   for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
643     ProgramPoint PP = N->getLocation();
644     if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
645       assert(N->pred_size() == 1);
646       continue;
647     }
648     SrcBlock = PP.castAs<BlockEdge>().getSrc();
649     break;
650   }
651 
652   assert(SrcBlock && "missing function entry");
653 
654   // Find the last expression in the predecessor block.  That is the
655   // expression that is used for the value of the ternary expression.
656   bool hasValue = false;
657   SVal V;
658 
659   for (CFGBlock::const_reverse_iterator I = SrcBlock->rbegin(),
660                                         E = SrcBlock->rend(); I != E; ++I) {
661     CFGElement CE = *I;
662     if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
663       const Expr *ValEx = cast<Expr>(CS->getStmt());
664       hasValue = true;
665       V = state->getSVal(ValEx, LCtx);
666       break;
667     }
668   }
669 
670   assert(hasValue);
671   (void) hasValue;
672 
673   // Generate a new node with the binding from the appropriate path.
674   B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
675 }
676 
677 void ExprEngine::
678 VisitOffsetOfExpr(const OffsetOfExpr *OOE,
679                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
680   StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
681   APSInt IV;
682   if (OOE->EvaluateAsInt(IV, getContext())) {
683     assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
684     assert(OOE->getType()->isIntegerType());
685     assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType());
686     SVal X = svalBuilder.makeIntVal(IV);
687     B.generateNode(OOE, Pred,
688                    Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
689                                               X));
690   }
691   // FIXME: Handle the case where __builtin_offsetof is not a constant.
692 }
693 
694 
695 void ExprEngine::
696 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
697                               ExplodedNode *Pred,
698                               ExplodedNodeSet &Dst) {
699   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
700 
701   QualType T = Ex->getTypeOfArgument();
702 
703   if (Ex->getKind() == UETT_SizeOf) {
704     if (!T->isIncompleteType() && !T->isConstantSizeType()) {
705       assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
706 
707       // FIXME: Add support for VLA type arguments and VLA expressions.
708       // When that happens, we should probably refactor VLASizeChecker's code.
709       return;
710     }
711     else if (T->getAs<ObjCObjectType>()) {
712       // Some code tries to take the sizeof an ObjCObjectType, relying that
713       // the compiler has laid out its representation.  Just report Unknown
714       // for these.
715       return;
716     }
717   }
718 
719   APSInt Value = Ex->EvaluateKnownConstInt(getContext());
720   CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
721 
722   ProgramStateRef state = Pred->getState();
723   state = state->BindExpr(Ex, Pred->getLocationContext(),
724                           svalBuilder.makeIntVal(amt.getQuantity(),
725                                                      Ex->getType()));
726   Bldr.generateNode(Ex, Pred, state);
727 }
728 
729 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
730                                     ExplodedNode *Pred,
731                                     ExplodedNodeSet &Dst) {
732   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
733   switch (U->getOpcode()) {
734     default: {
735       Bldr.takeNodes(Pred);
736       ExplodedNodeSet Tmp;
737       VisitIncrementDecrementOperator(U, Pred, Tmp);
738       Bldr.addNodes(Tmp);
739     }
740       break;
741     case UO_Real: {
742       const Expr *Ex = U->getSubExpr()->IgnoreParens();
743 
744       // FIXME: We don't have complex SValues yet.
745       if (Ex->getType()->isAnyComplexType()) {
746         // Just report "Unknown."
747         break;
748       }
749 
750       // For all other types, UO_Real is an identity operation.
751       assert (U->getType() == Ex->getType());
752       ProgramStateRef state = Pred->getState();
753       const LocationContext *LCtx = Pred->getLocationContext();
754       Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx,
755                                                  state->getSVal(Ex, LCtx)));
756       break;
757     }
758 
759     case UO_Imag: {
760       const Expr *Ex = U->getSubExpr()->IgnoreParens();
761       // FIXME: We don't have complex SValues yet.
762       if (Ex->getType()->isAnyComplexType()) {
763         // Just report "Unknown."
764         break;
765       }
766       // For all other types, UO_Imag returns 0.
767       ProgramStateRef state = Pred->getState();
768       const LocationContext *LCtx = Pred->getLocationContext();
769       SVal X = svalBuilder.makeZeroVal(Ex->getType());
770       Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, X));
771       break;
772     }
773 
774     case UO_Plus:
775       assert(!U->isGLValue());
776       // FALL-THROUGH.
777     case UO_Deref:
778     case UO_AddrOf:
779     case UO_Extension: {
780       // FIXME: We can probably just have some magic in Environment::getSVal()
781       // that propagates values, instead of creating a new node here.
782       //
783       // Unary "+" is a no-op, similar to a parentheses.  We still have places
784       // where it may be a block-level expression, so we need to
785       // generate an extra node that just propagates the value of the
786       // subexpression.
787       const Expr *Ex = U->getSubExpr()->IgnoreParens();
788       ProgramStateRef state = Pred->getState();
789       const LocationContext *LCtx = Pred->getLocationContext();
790       Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx,
791                                                  state->getSVal(Ex, LCtx)));
792       break;
793     }
794 
795     case UO_LNot:
796     case UO_Minus:
797     case UO_Not: {
798       assert (!U->isGLValue());
799       const Expr *Ex = U->getSubExpr()->IgnoreParens();
800       ProgramStateRef state = Pred->getState();
801       const LocationContext *LCtx = Pred->getLocationContext();
802 
803       // Get the value of the subexpression.
804       SVal V = state->getSVal(Ex, LCtx);
805 
806       if (V.isUnknownOrUndef()) {
807         Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, V));
808         break;
809       }
810 
811       switch (U->getOpcode()) {
812         default:
813           llvm_unreachable("Invalid Opcode.");
814         case UO_Not:
815           // FIXME: Do we need to handle promotions?
816           state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
817           break;
818         case UO_Minus:
819           // FIXME: Do we need to handle promotions?
820           state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
821           break;
822         case UO_LNot:
823           // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
824           //
825           //  Note: technically we do "E == 0", but this is the same in the
826           //    transfer functions as "0 == E".
827           SVal Result;
828           if (Optional<Loc> LV = V.getAs<Loc>()) {
829             Loc X = svalBuilder.makeNull();
830             Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
831           }
832           else if (Ex->getType()->isFloatingType()) {
833             // FIXME: handle floating point types.
834             Result = UnknownVal();
835           } else {
836             nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
837             Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
838                                U->getType());
839           }
840 
841           state = state->BindExpr(U, LCtx, Result);
842           break;
843       }
844       Bldr.generateNode(U, Pred, state);
845       break;
846     }
847   }
848 
849 }
850 
851 void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
852                                                  ExplodedNode *Pred,
853                                                  ExplodedNodeSet &Dst) {
854   // Handle ++ and -- (both pre- and post-increment).
855   assert (U->isIncrementDecrementOp());
856   const Expr *Ex = U->getSubExpr()->IgnoreParens();
857 
858   const LocationContext *LCtx = Pred->getLocationContext();
859   ProgramStateRef state = Pred->getState();
860   SVal loc = state->getSVal(Ex, LCtx);
861 
862   // Perform a load.
863   ExplodedNodeSet Tmp;
864   evalLoad(Tmp, U, Ex, Pred, state, loc);
865 
866   ExplodedNodeSet Dst2;
867   StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
868   for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
869 
870     state = (*I)->getState();
871     assert(LCtx == (*I)->getLocationContext());
872     SVal V2_untested = state->getSVal(Ex, LCtx);
873 
874     // Propagate unknown and undefined values.
875     if (V2_untested.isUnknownOrUndef()) {
876       Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
877       continue;
878     }
879     DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
880 
881     // Handle all other values.
882     BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
883 
884     // If the UnaryOperator has non-location type, use its type to create the
885     // constant value. If the UnaryOperator has location type, create the
886     // constant with int type and pointer width.
887     SVal RHS;
888 
889     if (U->getType()->isAnyPointerType())
890       RHS = svalBuilder.makeArrayIndex(1);
891     else if (U->getType()->isIntegralOrEnumerationType())
892       RHS = svalBuilder.makeIntVal(1, U->getType());
893     else
894       RHS = UnknownVal();
895 
896     SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
897 
898     // Conjure a new symbol if necessary to recover precision.
899     if (Result.isUnknown()){
900       DefinedOrUnknownSVal SymVal =
901         svalBuilder.conjureSymbolVal(0, Ex, LCtx, currBldrCtx->blockCount());
902       Result = SymVal;
903 
904       // If the value is a location, ++/-- should always preserve
905       // non-nullness.  Check if the original value was non-null, and if so
906       // propagate that constraint.
907       if (Loc::isLocType(U->getType())) {
908         DefinedOrUnknownSVal Constraint =
909         svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
910 
911         if (!state->assume(Constraint, true)) {
912           // It isn't feasible for the original value to be null.
913           // Propagate this constraint.
914           Constraint = svalBuilder.evalEQ(state, SymVal,
915                                        svalBuilder.makeZeroVal(U->getType()));
916 
917 
918           state = state->assume(Constraint, false);
919           assert(state);
920         }
921       }
922     }
923 
924     // Since the lvalue-to-rvalue conversion is explicit in the AST,
925     // we bind an l-value if the operator is prefix and an lvalue (in C++).
926     if (U->isGLValue())
927       state = state->BindExpr(U, LCtx, loc);
928     else
929       state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
930 
931     // Perform the store.
932     Bldr.takeNodes(*I);
933     ExplodedNodeSet Dst3;
934     evalStore(Dst3, U, U, *I, state, loc, Result);
935     Bldr.addNodes(Dst3);
936   }
937   Dst.insert(Dst2);
938 }
939