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