1 //===- SValBuilder.cpp - Basic class for all SValBuilder implementations --===//
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 SValBuilder, the base class for all (complete) SValBuilder
11 //  implementations.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/Stmt.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/LLVM.h"
24 #include "clang/Analysis/AnalysisDeclContext.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
34 #include "llvm/ADT/APSInt.h"
35 #include "llvm/ADT/None.h"
36 #include "llvm/ADT/Optional.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/Compiler.h"
39 #include <cassert>
40 #include <tuple>
41 
42 using namespace clang;
43 using namespace ento;
44 
45 //===----------------------------------------------------------------------===//
46 // Basic SVal creation.
47 //===----------------------------------------------------------------------===//
48 
49 void SValBuilder::anchor() {}
50 
51 DefinedOrUnknownSVal SValBuilder::makeZeroVal(QualType type) {
52   if (Loc::isLocType(type))
53     return makeNull();
54 
55   if (type->isIntegralOrEnumerationType())
56     return makeIntVal(0, type);
57 
58   if (type->isArrayType() || type->isRecordType() || type->isVectorType() ||
59       type->isAnyComplexType())
60     return makeCompoundVal(type, BasicVals.getEmptySValList());
61 
62   // FIXME: Handle floats.
63   return UnknownVal();
64 }
65 
66 NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
67                                 const llvm::APSInt& rhs, QualType type) {
68   // The Environment ensures we always get a persistent APSInt in
69   // BasicValueFactory, so we don't need to get the APSInt from
70   // BasicValueFactory again.
71   assert(lhs);
72   assert(!Loc::isLocType(type));
73   return nonloc::SymbolVal(SymMgr.getSymIntExpr(lhs, op, rhs, type));
74 }
75 
76 NonLoc SValBuilder::makeNonLoc(const llvm::APSInt& lhs,
77                                BinaryOperator::Opcode op, const SymExpr *rhs,
78                                QualType type) {
79   assert(rhs);
80   assert(!Loc::isLocType(type));
81   return nonloc::SymbolVal(SymMgr.getIntSymExpr(lhs, op, rhs, type));
82 }
83 
84 NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
85                                const SymExpr *rhs, QualType type) {
86   assert(lhs && rhs);
87   assert(!Loc::isLocType(type));
88   return nonloc::SymbolVal(SymMgr.getSymSymExpr(lhs, op, rhs, type));
89 }
90 
91 NonLoc SValBuilder::makeNonLoc(const SymExpr *operand,
92                                QualType fromTy, QualType toTy) {
93   assert(operand);
94   assert(!Loc::isLocType(toTy));
95   return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
96 }
97 
98 SVal SValBuilder::convertToArrayIndex(SVal val) {
99   if (val.isUnknownOrUndef())
100     return val;
101 
102   // Common case: we have an appropriately sized integer.
103   if (Optional<nonloc::ConcreteInt> CI = val.getAs<nonloc::ConcreteInt>()) {
104     const llvm::APSInt& I = CI->getValue();
105     if (I.getBitWidth() == ArrayIndexWidth && I.isSigned())
106       return val;
107   }
108 
109   return evalCastFromNonLoc(val.castAs<NonLoc>(), ArrayIndexTy);
110 }
111 
112 nonloc::ConcreteInt SValBuilder::makeBoolVal(const CXXBoolLiteralExpr *boolean){
113   return makeTruthVal(boolean->getValue());
114 }
115 
116 DefinedOrUnknownSVal
117 SValBuilder::getRegionValueSymbolVal(const TypedValueRegion *region) {
118   QualType T = region->getValueType();
119 
120   if (T->isNullPtrType())
121     return makeZeroVal(T);
122 
123   if (!SymbolManager::canSymbolicate(T))
124     return UnknownVal();
125 
126   SymbolRef sym = SymMgr.getRegionValueSymbol(region);
127 
128   if (Loc::isLocType(T))
129     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
130 
131   return nonloc::SymbolVal(sym);
132 }
133 
134 DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const void *SymbolTag,
135                                                    const Expr *Ex,
136                                                    const LocationContext *LCtx,
137                                                    unsigned Count) {
138   QualType T = Ex->getType();
139 
140   if (T->isNullPtrType())
141     return makeZeroVal(T);
142 
143   // Compute the type of the result. If the expression is not an R-value, the
144   // result should be a location.
145   QualType ExType = Ex->getType();
146   if (Ex->isGLValue())
147     T = LCtx->getAnalysisDeclContext()->getASTContext().getPointerType(ExType);
148 
149   return conjureSymbolVal(SymbolTag, Ex, LCtx, T, Count);
150 }
151 
152 DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const void *symbolTag,
153                                                    const Expr *expr,
154                                                    const LocationContext *LCtx,
155                                                    QualType type,
156                                                    unsigned count) {
157   if (type->isNullPtrType())
158     return makeZeroVal(type);
159 
160   if (!SymbolManager::canSymbolicate(type))
161     return UnknownVal();
162 
163   SymbolRef sym = SymMgr.conjureSymbol(expr, LCtx, type, count, symbolTag);
164 
165   if (Loc::isLocType(type))
166     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
167 
168   return nonloc::SymbolVal(sym);
169 }
170 
171 DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const Stmt *stmt,
172                                                    const LocationContext *LCtx,
173                                                    QualType type,
174                                                    unsigned visitCount) {
175   if (type->isNullPtrType())
176     return makeZeroVal(type);
177 
178   if (!SymbolManager::canSymbolicate(type))
179     return UnknownVal();
180 
181   SymbolRef sym = SymMgr.conjureSymbol(stmt, LCtx, type, visitCount);
182 
183   if (Loc::isLocType(type))
184     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
185 
186   return nonloc::SymbolVal(sym);
187 }
188 
189 DefinedOrUnknownSVal
190 SValBuilder::getConjuredHeapSymbolVal(const Expr *E,
191                                       const LocationContext *LCtx,
192                                       unsigned VisitCount) {
193   QualType T = E->getType();
194   assert(Loc::isLocType(T));
195   assert(SymbolManager::canSymbolicate(T));
196   if (T->isNullPtrType())
197     return makeZeroVal(T);
198 
199   SymbolRef sym = SymMgr.conjureSymbol(E, LCtx, T, VisitCount);
200   return loc::MemRegionVal(MemMgr.getSymbolicHeapRegion(sym));
201 }
202 
203 DefinedSVal SValBuilder::getMetadataSymbolVal(const void *symbolTag,
204                                               const MemRegion *region,
205                                               const Expr *expr, QualType type,
206                                               const LocationContext *LCtx,
207                                               unsigned count) {
208   assert(SymbolManager::canSymbolicate(type) && "Invalid metadata symbol type");
209 
210   SymbolRef sym =
211       SymMgr.getMetadataSymbol(region, expr, type, LCtx, count, symbolTag);
212 
213   if (Loc::isLocType(type))
214     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
215 
216   return nonloc::SymbolVal(sym);
217 }
218 
219 DefinedOrUnknownSVal
220 SValBuilder::getDerivedRegionValueSymbolVal(SymbolRef parentSymbol,
221                                              const TypedValueRegion *region) {
222   QualType T = region->getValueType();
223 
224   if (T->isNullPtrType())
225     return makeZeroVal(T);
226 
227   if (!SymbolManager::canSymbolicate(T))
228     return UnknownVal();
229 
230   SymbolRef sym = SymMgr.getDerivedSymbol(parentSymbol, region);
231 
232   if (Loc::isLocType(T))
233     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
234 
235   return nonloc::SymbolVal(sym);
236 }
237 
238 DefinedSVal SValBuilder::getMemberPointer(const DeclaratorDecl *DD) {
239   assert(!DD || isa<CXXMethodDecl>(DD) || isa<FieldDecl>(DD));
240 
241   if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DD)) {
242     // Sema treats pointers to static member functions as have function pointer
243     // type, so return a function pointer for the method.
244     // We don't need to play a similar trick for static member fields
245     // because these are represented as plain VarDecls and not FieldDecls
246     // in the AST.
247     if (MD->isStatic())
248       return getFunctionPointer(MD);
249   }
250 
251   return nonloc::PointerToMember(DD);
252 }
253 
254 DefinedSVal SValBuilder::getFunctionPointer(const FunctionDecl *func) {
255   return loc::MemRegionVal(MemMgr.getFunctionCodeRegion(func));
256 }
257 
258 DefinedSVal SValBuilder::getBlockPointer(const BlockDecl *block,
259                                          CanQualType locTy,
260                                          const LocationContext *locContext,
261                                          unsigned blockCount) {
262   const BlockCodeRegion *BC =
263     MemMgr.getBlockCodeRegion(block, locTy, locContext->getAnalysisDeclContext());
264   const BlockDataRegion *BD = MemMgr.getBlockDataRegion(BC, locContext,
265                                                         blockCount);
266   return loc::MemRegionVal(BD);
267 }
268 
269 /// Return a memory region for the 'this' object reference.
270 loc::MemRegionVal SValBuilder::getCXXThis(const CXXMethodDecl *D,
271                                           const StackFrameContext *SFC) {
272   return loc::MemRegionVal(getRegionManager().
273                            getCXXThisRegion(D->getThisType(getContext()), SFC));
274 }
275 
276 /// Return a memory region for the 'this' object reference.
277 loc::MemRegionVal SValBuilder::getCXXThis(const CXXRecordDecl *D,
278                                           const StackFrameContext *SFC) {
279   const Type *T = D->getTypeForDecl();
280   QualType PT = getContext().getPointerType(QualType(T, 0));
281   return loc::MemRegionVal(getRegionManager().getCXXThisRegion(PT, SFC));
282 }
283 
284 Optional<SVal> SValBuilder::getConstantVal(const Expr *E) {
285   E = E->IgnoreParens();
286 
287   switch (E->getStmtClass()) {
288   // Handle expressions that we treat differently from the AST's constant
289   // evaluator.
290   case Stmt::AddrLabelExprClass:
291     return makeLoc(cast<AddrLabelExpr>(E));
292 
293   case Stmt::CXXScalarValueInitExprClass:
294   case Stmt::ImplicitValueInitExprClass:
295     return makeZeroVal(E->getType());
296 
297   case Stmt::ObjCStringLiteralClass: {
298     const auto *SL = cast<ObjCStringLiteral>(E);
299     return makeLoc(getRegionManager().getObjCStringRegion(SL));
300   }
301 
302   case Stmt::StringLiteralClass: {
303     const auto *SL = cast<StringLiteral>(E);
304     return makeLoc(getRegionManager().getStringRegion(SL));
305   }
306 
307   // Fast-path some expressions to avoid the overhead of going through the AST's
308   // constant evaluator
309   case Stmt::CharacterLiteralClass: {
310     const auto *C = cast<CharacterLiteral>(E);
311     return makeIntVal(C->getValue(), C->getType());
312   }
313 
314   case Stmt::CXXBoolLiteralExprClass:
315     return makeBoolVal(cast<CXXBoolLiteralExpr>(E));
316 
317   case Stmt::TypeTraitExprClass: {
318     const auto *TE = cast<TypeTraitExpr>(E);
319     return makeTruthVal(TE->getValue(), TE->getType());
320   }
321 
322   case Stmt::IntegerLiteralClass:
323     return makeIntVal(cast<IntegerLiteral>(E));
324 
325   case Stmt::ObjCBoolLiteralExprClass:
326     return makeBoolVal(cast<ObjCBoolLiteralExpr>(E));
327 
328   case Stmt::CXXNullPtrLiteralExprClass:
329     return makeNull();
330 
331   case Stmt::CStyleCastExprClass:
332   case Stmt::CXXFunctionalCastExprClass:
333   case Stmt::CXXConstCastExprClass:
334   case Stmt::CXXReinterpretCastExprClass:
335   case Stmt::CXXStaticCastExprClass:
336   case Stmt::ImplicitCastExprClass: {
337     const auto *CE = cast<CastExpr>(E);
338     switch (CE->getCastKind()) {
339     default:
340       break;
341     case CK_ArrayToPointerDecay:
342     case CK_IntegralToPointer:
343     case CK_NoOp:
344     case CK_BitCast: {
345       const Expr *SE = CE->getSubExpr();
346       Optional<SVal> Val = getConstantVal(SE);
347       if (!Val)
348         return None;
349       return evalCast(*Val, CE->getType(), SE->getType());
350     }
351     }
352     // FALLTHROUGH
353     LLVM_FALLTHROUGH;
354   }
355 
356   // If we don't have a special case, fall back to the AST's constant evaluator.
357   default: {
358     // Don't try to come up with a value for materialized temporaries.
359     if (E->isGLValue())
360       return None;
361 
362     ASTContext &Ctx = getContext();
363     llvm::APSInt Result;
364     if (E->EvaluateAsInt(Result, Ctx))
365       return makeIntVal(Result);
366 
367     if (Loc::isLocType(E->getType()))
368       if (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
369         return makeNull();
370 
371     return None;
372   }
373   }
374 }
375 
376 SVal SValBuilder::makeSymExprValNN(ProgramStateRef State,
377                                    BinaryOperator::Opcode Op,
378                                    NonLoc LHS, NonLoc RHS,
379                                    QualType ResultTy) {
380   if (!State->isTainted(RHS) && !State->isTainted(LHS))
381     return UnknownVal();
382 
383   const SymExpr *symLHS = LHS.getAsSymExpr();
384   const SymExpr *symRHS = RHS.getAsSymExpr();
385   // TODO: When the Max Complexity is reached, we should conjure a symbol
386   // instead of generating an Unknown value and propagate the taint info to it.
387   const unsigned MaxComp = 10000; // 100000 28X
388 
389   if (symLHS && symRHS &&
390       (symLHS->computeComplexity() + symRHS->computeComplexity()) <  MaxComp)
391     return makeNonLoc(symLHS, Op, symRHS, ResultTy);
392 
393   if (symLHS && symLHS->computeComplexity() < MaxComp)
394     if (Optional<nonloc::ConcreteInt> rInt = RHS.getAs<nonloc::ConcreteInt>())
395       return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy);
396 
397   if (symRHS && symRHS->computeComplexity() < MaxComp)
398     if (Optional<nonloc::ConcreteInt> lInt = LHS.getAs<nonloc::ConcreteInt>())
399       return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy);
400 
401   return UnknownVal();
402 }
403 
404 SVal SValBuilder::evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
405                             SVal lhs, SVal rhs, QualType type) {
406   if (lhs.isUndef() || rhs.isUndef())
407     return UndefinedVal();
408 
409   if (lhs.isUnknown() || rhs.isUnknown())
410     return UnknownVal();
411 
412   if (lhs.getAs<nonloc::LazyCompoundVal>() ||
413       rhs.getAs<nonloc::LazyCompoundVal>()) {
414     return UnknownVal();
415   }
416 
417   if (Optional<Loc> LV = lhs.getAs<Loc>()) {
418     if (Optional<Loc> RV = rhs.getAs<Loc>())
419       return evalBinOpLL(state, op, *LV, *RV, type);
420 
421     return evalBinOpLN(state, op, *LV, rhs.castAs<NonLoc>(), type);
422   }
423 
424   if (Optional<Loc> RV = rhs.getAs<Loc>()) {
425     // Support pointer arithmetic where the addend is on the left
426     // and the pointer on the right.
427     assert(op == BO_Add);
428 
429     // Commute the operands.
430     return evalBinOpLN(state, op, *RV, lhs.castAs<NonLoc>(), type);
431   }
432 
433   return evalBinOpNN(state, op, lhs.castAs<NonLoc>(), rhs.castAs<NonLoc>(),
434                      type);
435 }
436 
437 ConditionTruthVal SValBuilder::areEqual(ProgramStateRef state, SVal lhs,
438                                         SVal rhs) {
439   return state->isNonNull(evalEQ(state, lhs, rhs));
440 }
441 
442 SVal SValBuilder::evalEQ(ProgramStateRef state, SVal lhs, SVal rhs) {
443   return evalBinOp(state, BO_EQ, lhs, rhs, getConditionType());
444 }
445 
446 DefinedOrUnknownSVal SValBuilder::evalEQ(ProgramStateRef state,
447                                          DefinedOrUnknownSVal lhs,
448                                          DefinedOrUnknownSVal rhs) {
449   return evalEQ(state, static_cast<SVal>(lhs), static_cast<SVal>(rhs))
450       .castAs<DefinedOrUnknownSVal>();
451 }
452 
453 /// Recursively check if the pointer types are equal modulo const, volatile,
454 /// and restrict qualifiers. Also, assume that all types are similar to 'void'.
455 /// Assumes the input types are canonical.
456 static bool shouldBeModeledWithNoOp(ASTContext &Context, QualType ToTy,
457                                                          QualType FromTy) {
458   while (Context.UnwrapSimilarPointerTypes(ToTy, FromTy)) {
459     Qualifiers Quals1, Quals2;
460     ToTy = Context.getUnqualifiedArrayType(ToTy, Quals1);
461     FromTy = Context.getUnqualifiedArrayType(FromTy, Quals2);
462 
463     // Make sure that non-cvr-qualifiers the other qualifiers (e.g., address
464     // spaces) are identical.
465     Quals1.removeCVRQualifiers();
466     Quals2.removeCVRQualifiers();
467     if (Quals1 != Quals2)
468       return false;
469   }
470 
471   // If we are casting to void, the 'From' value can be used to represent the
472   // 'To' value.
473   if (ToTy->isVoidType())
474     return true;
475 
476   if (ToTy != FromTy)
477     return false;
478 
479   return true;
480 }
481 
482 // Handles casts of type CK_IntegralCast.
483 // At the moment, this function will redirect to evalCast, except when the range
484 // of the original value is known to be greater than the max of the target type.
485 SVal SValBuilder::evalIntegralCast(ProgramStateRef state, SVal val,
486                                    QualType castTy, QualType originalTy) {
487   // No truncations if target type is big enough.
488   if (getContext().getTypeSize(castTy) >= getContext().getTypeSize(originalTy))
489     return evalCast(val, castTy, originalTy);
490 
491   const SymExpr *se = val.getAsSymbolicExpression();
492   if (!se) // Let evalCast handle non symbolic expressions.
493     return evalCast(val, castTy, originalTy);
494 
495   // Find the maximum value of the target type.
496   APSIntType ToType(getContext().getTypeSize(castTy),
497                     castTy->isUnsignedIntegerType());
498   llvm::APSInt ToTypeMax = ToType.getMaxValue();
499   NonLoc ToTypeMaxVal =
500       makeIntVal(ToTypeMax.isUnsigned() ? ToTypeMax.getZExtValue()
501                                         : ToTypeMax.getSExtValue(),
502                  castTy)
503           .castAs<NonLoc>();
504   // Check the range of the symbol being casted against the maximum value of the
505   // target type.
506   NonLoc FromVal = val.castAs<NonLoc>();
507   QualType CmpTy = getConditionType();
508   NonLoc CompVal =
509       evalBinOpNN(state, BO_LE, FromVal, ToTypeMaxVal, CmpTy).castAs<NonLoc>();
510   ProgramStateRef IsNotTruncated, IsTruncated;
511   std::tie(IsNotTruncated, IsTruncated) = state->assume(CompVal);
512   if (!IsNotTruncated && IsTruncated) {
513     // Symbol is truncated so we evaluate it as a cast.
514     NonLoc CastVal = makeNonLoc(se, originalTy, castTy);
515     return CastVal;
516   }
517   return evalCast(val, castTy, originalTy);
518 }
519 
520 // FIXME: should rewrite according to the cast kind.
521 SVal SValBuilder::evalCast(SVal val, QualType castTy, QualType originalTy) {
522   castTy = Context.getCanonicalType(castTy);
523   originalTy = Context.getCanonicalType(originalTy);
524   if (val.isUnknownOrUndef() || castTy == originalTy)
525     return val;
526 
527   if (castTy->isBooleanType()) {
528     if (val.isUnknownOrUndef())
529       return val;
530     if (val.isConstant())
531       return makeTruthVal(!val.isZeroConstant(), castTy);
532     if (!Loc::isLocType(originalTy) &&
533         !originalTy->isIntegralOrEnumerationType() &&
534         !originalTy->isMemberPointerType())
535       return UnknownVal();
536     if (SymbolRef Sym = val.getAsSymbol(true)) {
537       BasicValueFactory &BVF = getBasicValueFactory();
538       // FIXME: If we had a state here, we could see if the symbol is known to
539       // be zero, but we don't.
540       return makeNonLoc(Sym, BO_NE, BVF.getValue(0, Sym->getType()), castTy);
541     }
542     // Loc values are not always true, they could be weakly linked functions.
543     if (Optional<Loc> L = val.getAs<Loc>())
544       return evalCastFromLoc(*L, castTy);
545 
546     Loc L = val.castAs<nonloc::LocAsInteger>().getLoc();
547     return evalCastFromLoc(L, castTy);
548   }
549 
550   // For const casts, casts to void, just propagate the value.
551   if (!castTy->isVariableArrayType() && !originalTy->isVariableArrayType())
552     if (shouldBeModeledWithNoOp(Context, Context.getPointerType(castTy),
553                                          Context.getPointerType(originalTy)))
554       return val;
555 
556   // Check for casts from pointers to integers.
557   if (castTy->isIntegralOrEnumerationType() && Loc::isLocType(originalTy))
558     return evalCastFromLoc(val.castAs<Loc>(), castTy);
559 
560   // Check for casts from integers to pointers.
561   if (Loc::isLocType(castTy) && originalTy->isIntegralOrEnumerationType()) {
562     if (Optional<nonloc::LocAsInteger> LV = val.getAs<nonloc::LocAsInteger>()) {
563       if (const MemRegion *R = LV->getLoc().getAsRegion()) {
564         StoreManager &storeMgr = StateMgr.getStoreManager();
565         R = storeMgr.castRegion(R, castTy);
566         return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
567       }
568       return LV->getLoc();
569     }
570     return dispatchCast(val, castTy);
571   }
572 
573   // Just pass through function and block pointers.
574   if (originalTy->isBlockPointerType() || originalTy->isFunctionPointerType()) {
575     assert(Loc::isLocType(castTy));
576     return val;
577   }
578 
579   // Check for casts from array type to another type.
580   if (const auto *arrayT =
581           dyn_cast<ArrayType>(originalTy.getCanonicalType())) {
582     // We will always decay to a pointer.
583     QualType elemTy = arrayT->getElementType();
584     val = StateMgr.ArrayToPointer(val.castAs<Loc>(), elemTy);
585 
586     // Are we casting from an array to a pointer?  If so just pass on
587     // the decayed value.
588     if (castTy->isPointerType() || castTy->isReferenceType())
589       return val;
590 
591     // Are we casting from an array to an integer?  If so, cast the decayed
592     // pointer value to an integer.
593     assert(castTy->isIntegralOrEnumerationType());
594 
595     // FIXME: Keep these here for now in case we decide soon that we
596     // need the original decayed type.
597     //    QualType elemTy = cast<ArrayType>(originalTy)->getElementType();
598     //    QualType pointerTy = C.getPointerType(elemTy);
599     return evalCastFromLoc(val.castAs<Loc>(), castTy);
600   }
601 
602   // Check for casts from a region to a specific type.
603   if (const MemRegion *R = val.getAsRegion()) {
604     // Handle other casts of locations to integers.
605     if (castTy->isIntegralOrEnumerationType())
606       return evalCastFromLoc(loc::MemRegionVal(R), castTy);
607 
608     // FIXME: We should handle the case where we strip off view layers to get
609     //  to a desugared type.
610     if (!Loc::isLocType(castTy)) {
611       // FIXME: There can be gross cases where one casts the result of a function
612       // (that returns a pointer) to some other value that happens to fit
613       // within that pointer value.  We currently have no good way to
614       // model such operations.  When this happens, the underlying operation
615       // is that the caller is reasoning about bits.  Conceptually we are
616       // layering a "view" of a location on top of those bits.  Perhaps
617       // we need to be more lazy about mutual possible views, even on an
618       // SVal?  This may be necessary for bit-level reasoning as well.
619       return UnknownVal();
620     }
621 
622     // We get a symbolic function pointer for a dereference of a function
623     // pointer, but it is of function type. Example:
624 
625     //  struct FPRec {
626     //    void (*my_func)(int * x);
627     //  };
628     //
629     //  int bar(int x);
630     //
631     //  int f1_a(struct FPRec* foo) {
632     //    int x;
633     //    (*foo->my_func)(&x);
634     //    return bar(x)+1; // no-warning
635     //  }
636 
637     assert(Loc::isLocType(originalTy) || originalTy->isFunctionType() ||
638            originalTy->isBlockPointerType() || castTy->isReferenceType());
639 
640     StoreManager &storeMgr = StateMgr.getStoreManager();
641 
642     // Delegate to store manager to get the result of casting a region to a
643     // different type.  If the MemRegion* returned is NULL, this expression
644     // Evaluates to UnknownVal.
645     R = storeMgr.castRegion(R, castTy);
646     return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
647   }
648 
649   return dispatchCast(val, castTy);
650 }
651