1 // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- 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 SimpleSValBuilder, a basic implementation of SValBuilder.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
20 
21 using namespace clang;
22 using namespace ento;
23 
24 namespace {
25 class SimpleSValBuilder : public SValBuilder {
26 protected:
27   SVal dispatchCast(SVal val, QualType castTy) override;
28   SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
29   SVal evalCastFromLoc(Loc val, QualType castTy) override;
30 
31 public:
32   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
33                     ProgramStateManager &stateMgr)
34                     : SValBuilder(alloc, context, stateMgr) {}
35   ~SimpleSValBuilder() override {}
36 
37   SVal evalMinus(NonLoc val) override;
38   SVal evalComplement(NonLoc val) override;
39   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
40                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
41   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
42                    Loc lhs, Loc rhs, QualType resultTy) override;
43   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
44                    Loc lhs, NonLoc rhs, QualType resultTy) override;
45 
46   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
47   ///  (integer) value, that value is returned. Otherwise, returns NULL.
48   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
49 
50   /// Recursively descends into symbolic expressions and replaces symbols
51   /// with their known values (in the sense of the getKnownValue() method).
52   SVal simplifySVal(ProgramStateRef State, SVal V) override;
53 
54   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
55                      const llvm::APSInt &RHS, QualType resultTy);
56 };
57 } // end anonymous namespace
58 
59 SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
60                                            ASTContext &context,
61                                            ProgramStateManager &stateMgr) {
62   return new SimpleSValBuilder(alloc, context, stateMgr);
63 }
64 
65 //===----------------------------------------------------------------------===//
66 // Transfer function for Casts.
67 //===----------------------------------------------------------------------===//
68 
69 SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
70   assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
71   return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
72                            : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
73 }
74 
75 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
76   bool isLocType = Loc::isLocType(castTy);
77   if (val.getAs<nonloc::PointerToMember>())
78     return val;
79 
80   if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
81     if (isLocType)
82       return LI->getLoc();
83     // FIXME: Correctly support promotions/truncations.
84     unsigned castSize = Context.getIntWidth(castTy);
85     if (castSize == LI->getNumBits())
86       return val;
87     return makeLocAsInteger(LI->getLoc(), castSize);
88   }
89 
90   if (const SymExpr *se = val.getAsSymbolicExpression()) {
91     QualType T = Context.getCanonicalType(se->getType());
92     // If types are the same or both are integers, ignore the cast.
93     // FIXME: Remove this hack when we support symbolic truncation/extension.
94     // HACK: If both castTy and T are integers, ignore the cast.  This is
95     // not a permanent solution.  Eventually we want to precisely handle
96     // extension/truncation of symbolic integers.  This prevents us from losing
97     // precision when we assign 'x = y' and 'y' is symbolic and x and y are
98     // different integer types.
99    if (haveSameType(T, castTy))
100       return val;
101 
102     if (!isLocType)
103       return makeNonLoc(se, T, castTy);
104     return UnknownVal();
105   }
106 
107   // If value is a non-integer constant, produce unknown.
108   if (!val.getAs<nonloc::ConcreteInt>())
109     return UnknownVal();
110 
111   // Handle casts to a boolean type.
112   if (castTy->isBooleanType()) {
113     bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
114     return makeTruthVal(b, castTy);
115   }
116 
117   // Only handle casts from integers to integers - if val is an integer constant
118   // being cast to a non-integer type, produce unknown.
119   if (!isLocType && !castTy->isIntegralOrEnumerationType())
120     return UnknownVal();
121 
122   llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
123   BasicVals.getAPSIntType(castTy).apply(i);
124 
125   if (isLocType)
126     return makeIntLocVal(i);
127   else
128     return makeIntVal(i);
129 }
130 
131 SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
132 
133   // Casts from pointers -> pointers, just return the lval.
134   //
135   // Casts from pointers -> references, just return the lval.  These
136   //   can be introduced by the frontend for corner cases, e.g
137   //   casting from va_list* to __builtin_va_list&.
138   //
139   if (Loc::isLocType(castTy) || castTy->isReferenceType())
140     return val;
141 
142   // FIXME: Handle transparent unions where a value can be "transparently"
143   //  lifted into a union type.
144   if (castTy->isUnionType())
145     return UnknownVal();
146 
147   // Casting a Loc to a bool will almost always be true,
148   // unless this is a weak function or a symbolic region.
149   if (castTy->isBooleanType()) {
150     switch (val.getSubKind()) {
151       case loc::MemRegionValKind: {
152         const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
153         if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
154           if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
155             if (FD->isWeak())
156               // FIXME: Currently we are using an extent symbol here,
157               // because there are no generic region address metadata
158               // symbols to use, only content metadata.
159               return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
160 
161         if (const SymbolicRegion *SymR = R->getSymbolicBase())
162           return nonloc::SymbolVal(SymR->getSymbol());
163 
164         // FALL-THROUGH
165         LLVM_FALLTHROUGH;
166       }
167 
168       case loc::GotoLabelKind:
169         // Labels and non-symbolic memory regions are always true.
170         return makeTruthVal(true, castTy);
171     }
172   }
173 
174   if (castTy->isIntegralOrEnumerationType()) {
175     unsigned BitWidth = Context.getIntWidth(castTy);
176 
177     if (!val.getAs<loc::ConcreteInt>())
178       return makeLocAsInteger(val, BitWidth);
179 
180     llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
181     BasicVals.getAPSIntType(castTy).apply(i);
182     return makeIntVal(i);
183   }
184 
185   // All other cases: return 'UnknownVal'.  This includes casting pointers
186   // to floats, which is probably badness it itself, but this is a good
187   // intermediate solution until we do something better.
188   return UnknownVal();
189 }
190 
191 //===----------------------------------------------------------------------===//
192 // Transfer function for unary operators.
193 //===----------------------------------------------------------------------===//
194 
195 SVal SimpleSValBuilder::evalMinus(NonLoc val) {
196   switch (val.getSubKind()) {
197   case nonloc::ConcreteIntKind:
198     return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
199   default:
200     return UnknownVal();
201   }
202 }
203 
204 SVal SimpleSValBuilder::evalComplement(NonLoc X) {
205   switch (X.getSubKind()) {
206   case nonloc::ConcreteIntKind:
207     return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
208   default:
209     return UnknownVal();
210   }
211 }
212 
213 //===----------------------------------------------------------------------===//
214 // Transfer function for binary operators.
215 //===----------------------------------------------------------------------===//
216 
217 SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
218                                     BinaryOperator::Opcode op,
219                                     const llvm::APSInt &RHS,
220                                     QualType resultTy) {
221   bool isIdempotent = false;
222 
223   // Check for a few special cases with known reductions first.
224   switch (op) {
225   default:
226     // We can't reduce this case; just treat it normally.
227     break;
228   case BO_Mul:
229     // a*0 and a*1
230     if (RHS == 0)
231       return makeIntVal(0, resultTy);
232     else if (RHS == 1)
233       isIdempotent = true;
234     break;
235   case BO_Div:
236     // a/0 and a/1
237     if (RHS == 0)
238       // This is also handled elsewhere.
239       return UndefinedVal();
240     else if (RHS == 1)
241       isIdempotent = true;
242     break;
243   case BO_Rem:
244     // a%0 and a%1
245     if (RHS == 0)
246       // This is also handled elsewhere.
247       return UndefinedVal();
248     else if (RHS == 1)
249       return makeIntVal(0, resultTy);
250     break;
251   case BO_Add:
252   case BO_Sub:
253   case BO_Shl:
254   case BO_Shr:
255   case BO_Xor:
256     // a+0, a-0, a<<0, a>>0, a^0
257     if (RHS == 0)
258       isIdempotent = true;
259     break;
260   case BO_And:
261     // a&0 and a&(~0)
262     if (RHS == 0)
263       return makeIntVal(0, resultTy);
264     else if (RHS.isAllOnesValue())
265       isIdempotent = true;
266     break;
267   case BO_Or:
268     // a|0 and a|(~0)
269     if (RHS == 0)
270       isIdempotent = true;
271     else if (RHS.isAllOnesValue()) {
272       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
273       return nonloc::ConcreteInt(Result);
274     }
275     break;
276   }
277 
278   // Idempotent ops (like a*1) can still change the type of an expression.
279   // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
280   // dirty work.
281   if (isIdempotent)
282       return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
283 
284   // If we reach this point, the expression cannot be simplified.
285   // Make a SymbolVal for the entire expression, after converting the RHS.
286   const llvm::APSInt *ConvertedRHS = &RHS;
287   if (BinaryOperator::isComparisonOp(op)) {
288     // We're looking for a type big enough to compare the symbolic value
289     // with the given constant.
290     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
291     ASTContext &Ctx = getContext();
292     QualType SymbolType = LHS->getType();
293     uint64_t ValWidth = RHS.getBitWidth();
294     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
295 
296     if (ValWidth < TypeWidth) {
297       // If the value is too small, extend it.
298       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
299     } else if (ValWidth == TypeWidth) {
300       // If the value is signed but the symbol is unsigned, do the comparison
301       // in unsigned space. [C99 6.3.1.8]
302       // (For the opposite case, the value is already unsigned.)
303       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
304         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
305     }
306   } else
307     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
308 
309   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
310 }
311 
312 // See if Sym is known to be a relation Rel with Bound.
313 static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
314                          llvm::APSInt Bound, ProgramStateRef State) {
315   SValBuilder &SVB = State->getStateManager().getSValBuilder();
316   SVal Result =
317       SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
318                       nonloc::ConcreteInt(Bound), SVB.getConditionType());
319   if (auto DV = Result.getAs<DefinedSVal>()) {
320     return !State->assume(*DV, false);
321   }
322   return false;
323 }
324 
325 // See if Sym is known to be within [min/4, max/4], where min and max
326 // are the bounds of the symbol's integral type. With such symbols,
327 // some manipulations can be performed without the risk of overflow.
328 // assume() doesn't cause infinite recursion because we should be dealing
329 // with simpler symbols on every recursive call.
330 static bool isWithinConstantOverflowBounds(SymbolRef Sym,
331                                            ProgramStateRef State) {
332   SValBuilder &SVB = State->getStateManager().getSValBuilder();
333   BasicValueFactory &BV = SVB.getBasicValueFactory();
334 
335   QualType T = Sym->getType();
336   assert(T->isSignedIntegerOrEnumerationType() &&
337          "This only works with signed integers!");
338   APSIntType AT = BV.getAPSIntType(T);
339 
340   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
341   return isInRelation(BO_LE, Sym, Max, State) &&
342          isInRelation(BO_GE, Sym, Min, State);
343 }
344 
345 // Same for the concrete integers: see if I is within [min/4, max/4].
346 static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
347   APSIntType AT(I);
348   assert(!AT.isUnsigned() &&
349          "This only works with signed integers!");
350 
351   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
352   return (I <= Max) && (I >= -Max);
353 }
354 
355 static std::pair<SymbolRef, llvm::APSInt>
356 decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
357   if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
358     if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
359       return std::make_pair(SymInt->getLHS(),
360                             (SymInt->getOpcode() == BO_Add) ?
361                             (SymInt->getRHS()) :
362                             (-SymInt->getRHS()));
363 
364   // Fail to decompose: "reduce" the problem to the "$x + 0" case.
365   return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
366 }
367 
368 // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
369 // same signed integral type and no overflows occur (which should be checked
370 // by the caller).
371 static NonLoc doRearrangeUnchecked(ProgramStateRef State,
372                                    BinaryOperator::Opcode Op,
373                                    SymbolRef LSym, llvm::APSInt LInt,
374                                    SymbolRef RSym, llvm::APSInt RInt) {
375   SValBuilder &SVB = State->getStateManager().getSValBuilder();
376   BasicValueFactory &BV = SVB.getBasicValueFactory();
377   SymbolManager &SymMgr = SVB.getSymbolManager();
378 
379   QualType SymTy = LSym->getType();
380   assert(SymTy == RSym->getType() &&
381          "Symbols are not of the same type!");
382   assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
383          "Integers are not of the same type as symbols!");
384   assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
385          "Integers are not of the same type as symbols!");
386 
387   QualType ResultTy;
388   if (BinaryOperator::isComparisonOp(Op))
389     ResultTy = SVB.getConditionType();
390   else if (BinaryOperator::isAdditiveOp(Op))
391     ResultTy = SymTy;
392   else
393     llvm_unreachable("Operation not suitable for unchecked rearrangement!");
394 
395   // FIXME: Can we use assume() without getting into an infinite recursion?
396   if (LSym == RSym)
397     return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
398                            nonloc::ConcreteInt(RInt), ResultTy)
399         .castAs<NonLoc>();
400 
401   SymbolRef ResultSym = nullptr;
402   BinaryOperator::Opcode ResultOp;
403   llvm::APSInt ResultInt;
404   if (BinaryOperator::isComparisonOp(Op)) {
405     // Prefer comparing to a non-negative number.
406     // FIXME: Maybe it'd be better to have consistency in
407     // "$x - $y" vs. "$y - $x" because those are solver's keys.
408     if (LInt > RInt) {
409       ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
410       ResultOp = BinaryOperator::reverseComparisonOp(Op);
411       ResultInt = LInt - RInt; // Opposite order!
412     } else {
413       ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
414       ResultOp = Op;
415       ResultInt = RInt - LInt; // Opposite order!
416     }
417   } else {
418     ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
419     ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
420     ResultOp = BO_Add;
421     // Bring back the cosmetic difference.
422     if (ResultInt < 0) {
423       ResultInt = -ResultInt;
424       ResultOp = BO_Sub;
425     } else if (ResultInt == 0) {
426       // Shortcut: Simplify "$x + 0" to "$x".
427       return nonloc::SymbolVal(ResultSym);
428     }
429   }
430   const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
431   return nonloc::SymbolVal(
432       SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
433 }
434 
435 // Rearrange if symbol type matches the result type and if the operator is a
436 // comparison operator, both symbol and constant must be within constant
437 // overflow bounds.
438 static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
439                             SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
440   return Sym->getType() == Ty &&
441     (!BinaryOperator::isComparisonOp(Op) ||
442      (isWithinConstantOverflowBounds(Sym, State) &&
443       isWithinConstantOverflowBounds(Int)));
444 }
445 
446 static Optional<NonLoc> tryRearrange(ProgramStateRef State,
447                                      BinaryOperator::Opcode Op, NonLoc Lhs,
448                                      NonLoc Rhs, QualType ResultTy) {
449   ProgramStateManager &StateMgr = State->getStateManager();
450   SValBuilder &SVB = StateMgr.getSValBuilder();
451 
452   // We expect everything to be of the same type - this type.
453   QualType SingleTy;
454 
455   auto &Opts =
456     StateMgr.getOwningEngine()->getAnalysisManager().getAnalyzerOptions();
457 
458   SymbolRef LSym = Lhs.getAsSymbol();
459   if (!LSym)
460     return None;
461 
462   // Always rearrange additive operations but rearrange comparisons only if
463   // option is set.
464   if (BinaryOperator::isComparisonOp(Op) &&
465       Opts.shouldAggressivelySimplifyRelationalComparison()) {
466     SingleTy = LSym->getType();
467     if (ResultTy != SVB.getConditionType())
468       return None;
469     // Initialize SingleTy later with a symbol's type.
470   } else if (BinaryOperator::isAdditiveOp(Op)) {
471     SingleTy = ResultTy;
472     // Substracting unsigned integers is a nightmare.
473     if (!SingleTy->isSignedIntegerOrEnumerationType())
474       return None;
475   } else {
476     // Don't rearrange other operations.
477     return None;
478   }
479 
480   assert(!SingleTy.isNull() && "We should have figured out the type by now!");
481 
482   SymbolRef RSym = Rhs.getAsSymbol();
483   if (!RSym || RSym->getType() != SingleTy)
484     return None;
485 
486   BasicValueFactory &BV = State->getBasicVals();
487   llvm::APSInt LInt, RInt;
488   std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
489   std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
490   if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
491       !shouldRearrange(State, Op, RSym, RInt, SingleTy))
492     return None;
493 
494   // We know that no overflows can occur anymore.
495   return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
496 }
497 
498 SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
499                                   BinaryOperator::Opcode op,
500                                   NonLoc lhs, NonLoc rhs,
501                                   QualType resultTy)  {
502   NonLoc InputLHS = lhs;
503   NonLoc InputRHS = rhs;
504 
505   // Handle trivial case where left-side and right-side are the same.
506   if (lhs == rhs)
507     switch (op) {
508       default:
509         break;
510       case BO_EQ:
511       case BO_LE:
512       case BO_GE:
513         return makeTruthVal(true, resultTy);
514       case BO_LT:
515       case BO_GT:
516       case BO_NE:
517         return makeTruthVal(false, resultTy);
518       case BO_Xor:
519       case BO_Sub:
520         if (resultTy->isIntegralOrEnumerationType())
521           return makeIntVal(0, resultTy);
522         return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
523       case BO_Or:
524       case BO_And:
525         return evalCastFromNonLoc(lhs, resultTy);
526     }
527 
528   while (1) {
529     switch (lhs.getSubKind()) {
530     default:
531       return makeSymExprValNN(state, op, lhs, rhs, resultTy);
532     case nonloc::PointerToMemberKind: {
533       assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
534              "Both SVals should have pointer-to-member-type");
535       auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
536            RPTM = rhs.castAs<nonloc::PointerToMember>();
537       auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
538       switch (op) {
539         case BO_EQ:
540           return makeTruthVal(LPTMD == RPTMD, resultTy);
541         case BO_NE:
542           return makeTruthVal(LPTMD != RPTMD, resultTy);
543         default:
544           return UnknownVal();
545       }
546     }
547     case nonloc::LocAsIntegerKind: {
548       Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
549       switch (rhs.getSubKind()) {
550         case nonloc::LocAsIntegerKind:
551           // FIXME: at the moment the implementation
552           // of modeling "pointers as integers" is not complete.
553           if (!BinaryOperator::isComparisonOp(op))
554             return UnknownVal();
555           return evalBinOpLL(state, op, lhsL,
556                              rhs.castAs<nonloc::LocAsInteger>().getLoc(),
557                              resultTy);
558         case nonloc::ConcreteIntKind: {
559           // FIXME: at the moment the implementation
560           // of modeling "pointers as integers" is not complete.
561           if (!BinaryOperator::isComparisonOp(op))
562             return UnknownVal();
563           // Transform the integer into a location and compare.
564           // FIXME: This only makes sense for comparisons. If we want to, say,
565           // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
566           // then pack it back into a LocAsInteger.
567           llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
568           BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
569           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
570         }
571         default:
572           switch (op) {
573             case BO_EQ:
574               return makeTruthVal(false, resultTy);
575             case BO_NE:
576               return makeTruthVal(true, resultTy);
577             default:
578               // This case also handles pointer arithmetic.
579               return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
580           }
581       }
582     }
583     case nonloc::ConcreteIntKind: {
584       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
585 
586       // If we're dealing with two known constants, just perform the operation.
587       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
588         llvm::APSInt RHSValue = *KnownRHSValue;
589         if (BinaryOperator::isComparisonOp(op)) {
590           // We're looking for a type big enough to compare the two values.
591           // FIXME: This is not correct. char + short will result in a promotion
592           // to int. Unfortunately we have lost types by this point.
593           APSIntType CompareType = std::max(APSIntType(LHSValue),
594                                             APSIntType(RHSValue));
595           CompareType.apply(LHSValue);
596           CompareType.apply(RHSValue);
597         } else if (!BinaryOperator::isShiftOp(op)) {
598           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
599           IntType.apply(LHSValue);
600           IntType.apply(RHSValue);
601         }
602 
603         const llvm::APSInt *Result =
604           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
605         if (!Result)
606           return UndefinedVal();
607 
608         return nonloc::ConcreteInt(*Result);
609       }
610 
611       // Swap the left and right sides and flip the operator if doing so
612       // allows us to better reason about the expression (this is a form
613       // of expression canonicalization).
614       // While we're at it, catch some special cases for non-commutative ops.
615       switch (op) {
616       case BO_LT:
617       case BO_GT:
618       case BO_LE:
619       case BO_GE:
620         op = BinaryOperator::reverseComparisonOp(op);
621         // FALL-THROUGH
622       case BO_EQ:
623       case BO_NE:
624       case BO_Add:
625       case BO_Mul:
626       case BO_And:
627       case BO_Xor:
628       case BO_Or:
629         std::swap(lhs, rhs);
630         continue;
631       case BO_Shr:
632         // (~0)>>a
633         if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
634           return evalCastFromNonLoc(lhs, resultTy);
635         // FALL-THROUGH
636       case BO_Shl:
637         // 0<<a and 0>>a
638         if (LHSValue == 0)
639           return evalCastFromNonLoc(lhs, resultTy);
640         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
641       default:
642         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
643       }
644     }
645     case nonloc::SymbolValKind: {
646       // We only handle LHS as simple symbols or SymIntExprs.
647       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
648 
649       // LHS is a symbolic expression.
650       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
651 
652         // Is this a logical not? (!x is represented as x == 0.)
653         if (op == BO_EQ && rhs.isZeroConstant()) {
654           // We know how to negate certain expressions. Simplify them here.
655 
656           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
657           switch (opc) {
658           default:
659             // We don't know how to negate this operation.
660             // Just handle it as if it were a normal comparison to 0.
661             break;
662           case BO_LAnd:
663           case BO_LOr:
664             llvm_unreachable("Logical operators handled by branching logic.");
665           case BO_Assign:
666           case BO_MulAssign:
667           case BO_DivAssign:
668           case BO_RemAssign:
669           case BO_AddAssign:
670           case BO_SubAssign:
671           case BO_ShlAssign:
672           case BO_ShrAssign:
673           case BO_AndAssign:
674           case BO_XorAssign:
675           case BO_OrAssign:
676           case BO_Comma:
677             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
678           case BO_PtrMemD:
679           case BO_PtrMemI:
680             llvm_unreachable("Pointer arithmetic not handled here.");
681           case BO_LT:
682           case BO_GT:
683           case BO_LE:
684           case BO_GE:
685           case BO_EQ:
686           case BO_NE:
687             assert(resultTy->isBooleanType() ||
688                    resultTy == getConditionType());
689             assert(symIntExpr->getType()->isBooleanType() ||
690                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
691                                                        getConditionType()));
692             // Negate the comparison and make a value.
693             opc = BinaryOperator::negateComparisonOp(opc);
694             return makeNonLoc(symIntExpr->getLHS(), opc,
695                 symIntExpr->getRHS(), resultTy);
696           }
697         }
698 
699         // For now, only handle expressions whose RHS is a constant.
700         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
701           // If both the LHS and the current expression are additive,
702           // fold their constants and try again.
703           if (BinaryOperator::isAdditiveOp(op)) {
704             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
705             if (BinaryOperator::isAdditiveOp(lop)) {
706               // Convert the two constants to a common type, then combine them.
707 
708               // resultTy may not be the best type to convert to, but it's
709               // probably the best choice in expressions with mixed type
710               // (such as x+1U+2LL). The rules for implicit conversions should
711               // choose a reasonable type to preserve the expression, and will
712               // at least match how the value is going to be used.
713               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
714               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
715               const llvm::APSInt &second = IntType.convert(*RHSValue);
716 
717               const llvm::APSInt *newRHS;
718               if (lop == op)
719                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
720               else
721                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
722 
723               assert(newRHS && "Invalid operation despite common type!");
724               rhs = nonloc::ConcreteInt(*newRHS);
725               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
726               op = lop;
727               continue;
728             }
729           }
730 
731           // Otherwise, make a SymIntExpr out of the expression.
732           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
733         }
734       }
735 
736       // Does the symbolic expression simplify to a constant?
737       // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
738       // and try again.
739       SVal simplifiedLhs = simplifySVal(state, lhs);
740       if (simplifiedLhs != lhs)
741         if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
742           lhs = *simplifiedLhsAsNonLoc;
743           continue;
744         }
745 
746       // Is the RHS a constant?
747       if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
748         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
749 
750       if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
751         return *V;
752 
753       // Give up -- this is not a symbolic expression we can handle.
754       return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
755     }
756     }
757   }
758 }
759 
760 static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
761                                             const FieldRegion *RightFR,
762                                             BinaryOperator::Opcode op,
763                                             QualType resultTy,
764                                             SimpleSValBuilder &SVB) {
765   // Only comparisons are meaningful here!
766   if (!BinaryOperator::isComparisonOp(op))
767     return UnknownVal();
768 
769   // Next, see if the two FRs have the same super-region.
770   // FIXME: This doesn't handle casts yet, and simply stripping the casts
771   // doesn't help.
772   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
773     return UnknownVal();
774 
775   const FieldDecl *LeftFD = LeftFR->getDecl();
776   const FieldDecl *RightFD = RightFR->getDecl();
777   const RecordDecl *RD = LeftFD->getParent();
778 
779   // Make sure the two FRs are from the same kind of record. Just in case!
780   // FIXME: This is probably where inheritance would be a problem.
781   if (RD != RightFD->getParent())
782     return UnknownVal();
783 
784   // We know for sure that the two fields are not the same, since that
785   // would have given us the same SVal.
786   if (op == BO_EQ)
787     return SVB.makeTruthVal(false, resultTy);
788   if (op == BO_NE)
789     return SVB.makeTruthVal(true, resultTy);
790 
791   // Iterate through the fields and see which one comes first.
792   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
793   // members and the units in which bit-fields reside have addresses that
794   // increase in the order in which they are declared."
795   bool leftFirst = (op == BO_LT || op == BO_LE);
796   for (const auto *I : RD->fields()) {
797     if (I == LeftFD)
798       return SVB.makeTruthVal(leftFirst, resultTy);
799     if (I == RightFD)
800       return SVB.makeTruthVal(!leftFirst, resultTy);
801   }
802 
803   llvm_unreachable("Fields not found in parent record's definition");
804 }
805 
806 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
807 SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
808                                   BinaryOperator::Opcode op,
809                                   Loc lhs, Loc rhs,
810                                   QualType resultTy) {
811   // Only comparisons and subtractions are valid operations on two pointers.
812   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
813   // However, if a pointer is casted to an integer, evalBinOpNN may end up
814   // calling this function with another operation (PR7527). We don't attempt to
815   // model this for now, but it could be useful, particularly when the
816   // "location" is actually an integer value that's been passed through a void*.
817   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
818     return UnknownVal();
819 
820   // Special cases for when both sides are identical.
821   if (lhs == rhs) {
822     switch (op) {
823     default:
824       llvm_unreachable("Unimplemented operation for two identical values");
825     case BO_Sub:
826       return makeZeroVal(resultTy);
827     case BO_EQ:
828     case BO_LE:
829     case BO_GE:
830       return makeTruthVal(true, resultTy);
831     case BO_NE:
832     case BO_LT:
833     case BO_GT:
834       return makeTruthVal(false, resultTy);
835     }
836   }
837 
838   switch (lhs.getSubKind()) {
839   default:
840     llvm_unreachable("Ordering not implemented for this Loc.");
841 
842   case loc::GotoLabelKind:
843     // The only thing we know about labels is that they're non-null.
844     if (rhs.isZeroConstant()) {
845       switch (op) {
846       default:
847         break;
848       case BO_Sub:
849         return evalCastFromLoc(lhs, resultTy);
850       case BO_EQ:
851       case BO_LE:
852       case BO_LT:
853         return makeTruthVal(false, resultTy);
854       case BO_NE:
855       case BO_GT:
856       case BO_GE:
857         return makeTruthVal(true, resultTy);
858       }
859     }
860     // There may be two labels for the same location, and a function region may
861     // have the same address as a label at the start of the function (depending
862     // on the ABI).
863     // FIXME: we can probably do a comparison against other MemRegions, though.
864     // FIXME: is there a way to tell if two labels refer to the same location?
865     return UnknownVal();
866 
867   case loc::ConcreteIntKind: {
868     // If one of the operands is a symbol and the other is a constant,
869     // build an expression for use by the constraint manager.
870     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
871       // We can only build expressions with symbols on the left,
872       // so we need a reversible operator.
873       if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
874         return UnknownVal();
875 
876       const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
877       op = BinaryOperator::reverseComparisonOp(op);
878       return makeNonLoc(rSym, op, lVal, resultTy);
879     }
880 
881     // If both operands are constants, just perform the operation.
882     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
883       SVal ResultVal =
884           lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
885       if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
886         return evalCastFromNonLoc(*Result, resultTy);
887 
888       assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
889       return UnknownVal();
890     }
891 
892     // Special case comparisons against NULL.
893     // This must come after the test if the RHS is a symbol, which is used to
894     // build constraints. The address of any non-symbolic region is guaranteed
895     // to be non-NULL, as is any label.
896     assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
897     if (lhs.isZeroConstant()) {
898       switch (op) {
899       default:
900         break;
901       case BO_EQ:
902       case BO_GT:
903       case BO_GE:
904         return makeTruthVal(false, resultTy);
905       case BO_NE:
906       case BO_LT:
907       case BO_LE:
908         return makeTruthVal(true, resultTy);
909       }
910     }
911 
912     // Comparing an arbitrary integer to a region or label address is
913     // completely unknowable.
914     return UnknownVal();
915   }
916   case loc::MemRegionValKind: {
917     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
918       // If one of the operands is a symbol and the other is a constant,
919       // build an expression for use by the constraint manager.
920       if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
921         if (BinaryOperator::isComparisonOp(op))
922           return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
923         return UnknownVal();
924       }
925       // Special case comparisons to NULL.
926       // This must come after the test if the LHS is a symbol, which is used to
927       // build constraints. The address of any non-symbolic region is guaranteed
928       // to be non-NULL.
929       if (rInt->isZeroConstant()) {
930         if (op == BO_Sub)
931           return evalCastFromLoc(lhs, resultTy);
932 
933         if (BinaryOperator::isComparisonOp(op)) {
934           QualType boolType = getContext().BoolTy;
935           NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
936           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
937           return evalBinOpNN(state, op, l, r, resultTy);
938         }
939       }
940 
941       // Comparing a region to an arbitrary integer is completely unknowable.
942       return UnknownVal();
943     }
944 
945     // Get both values as regions, if possible.
946     const MemRegion *LeftMR = lhs.getAsRegion();
947     assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
948 
949     const MemRegion *RightMR = rhs.getAsRegion();
950     if (!RightMR)
951       // The RHS is probably a label, which in theory could address a region.
952       // FIXME: we can probably make a more useful statement about non-code
953       // regions, though.
954       return UnknownVal();
955 
956     const MemRegion *LeftBase = LeftMR->getBaseRegion();
957     const MemRegion *RightBase = RightMR->getBaseRegion();
958     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
959     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
960     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
961 
962     // If the two regions are from different known memory spaces they cannot be
963     // equal. Also, assume that no symbolic region (whose memory space is
964     // unknown) is on the stack.
965     if (LeftMS != RightMS &&
966         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
967          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
968       switch (op) {
969       default:
970         return UnknownVal();
971       case BO_EQ:
972         return makeTruthVal(false, resultTy);
973       case BO_NE:
974         return makeTruthVal(true, resultTy);
975       }
976     }
977 
978     // If both values wrap regions, see if they're from different base regions.
979     // Note, heap base symbolic regions are assumed to not alias with
980     // each other; for example, we assume that malloc returns different address
981     // on each invocation.
982     // FIXME: ObjC object pointers always reside on the heap, but currently
983     // we treat their memory space as unknown, because symbolic pointers
984     // to ObjC objects may alias. There should be a way to construct
985     // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
986     // guesses memory space for ObjC object pointers manually instead of
987     // relying on us.
988     if (LeftBase != RightBase &&
989         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
990          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
991       switch (op) {
992       default:
993         return UnknownVal();
994       case BO_EQ:
995         return makeTruthVal(false, resultTy);
996       case BO_NE:
997         return makeTruthVal(true, resultTy);
998       }
999     }
1000 
1001     // Handle special cases for when both regions are element regions.
1002     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
1003     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
1004     if (RightER && LeftER) {
1005       // Next, see if the two ERs have the same super-region and matching types.
1006       // FIXME: This should do something useful even if the types don't match,
1007       // though if both indexes are constant the RegionRawOffset path will
1008       // give the correct answer.
1009       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
1010           LeftER->getElementType() == RightER->getElementType()) {
1011         // Get the left index and cast it to the correct type.
1012         // If the index is unknown or undefined, bail out here.
1013         SVal LeftIndexVal = LeftER->getIndex();
1014         Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
1015         if (!LeftIndex)
1016           return UnknownVal();
1017         LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
1018         LeftIndex = LeftIndexVal.getAs<NonLoc>();
1019         if (!LeftIndex)
1020           return UnknownVal();
1021 
1022         // Do the same for the right index.
1023         SVal RightIndexVal = RightER->getIndex();
1024         Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
1025         if (!RightIndex)
1026           return UnknownVal();
1027         RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
1028         RightIndex = RightIndexVal.getAs<NonLoc>();
1029         if (!RightIndex)
1030           return UnknownVal();
1031 
1032         // Actually perform the operation.
1033         // evalBinOpNN expects the two indexes to already be the right type.
1034         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
1035       }
1036     }
1037 
1038     // Special handling of the FieldRegions, even with symbolic offsets.
1039     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
1040     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
1041     if (RightFR && LeftFR) {
1042       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
1043                                                *this);
1044       if (!R.isUnknown())
1045         return R;
1046     }
1047 
1048     // Compare the regions using the raw offsets.
1049     RegionOffset LeftOffset = LeftMR->getAsOffset();
1050     RegionOffset RightOffset = RightMR->getAsOffset();
1051 
1052     if (LeftOffset.getRegion() != nullptr &&
1053         LeftOffset.getRegion() == RightOffset.getRegion() &&
1054         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
1055       int64_t left = LeftOffset.getOffset();
1056       int64_t right = RightOffset.getOffset();
1057 
1058       switch (op) {
1059         default:
1060           return UnknownVal();
1061         case BO_LT:
1062           return makeTruthVal(left < right, resultTy);
1063         case BO_GT:
1064           return makeTruthVal(left > right, resultTy);
1065         case BO_LE:
1066           return makeTruthVal(left <= right, resultTy);
1067         case BO_GE:
1068           return makeTruthVal(left >= right, resultTy);
1069         case BO_EQ:
1070           return makeTruthVal(left == right, resultTy);
1071         case BO_NE:
1072           return makeTruthVal(left != right, resultTy);
1073       }
1074     }
1075 
1076     // At this point we're not going to get a good answer, but we can try
1077     // conjuring an expression instead.
1078     SymbolRef LHSSym = lhs.getAsLocSymbol();
1079     SymbolRef RHSSym = rhs.getAsLocSymbol();
1080     if (LHSSym && RHSSym)
1081       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
1082 
1083     // If we get here, we have no way of comparing the regions.
1084     return UnknownVal();
1085   }
1086   }
1087 }
1088 
1089 SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
1090                                   BinaryOperator::Opcode op,
1091                                   Loc lhs, NonLoc rhs, QualType resultTy) {
1092   if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
1093     if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
1094       if (PTMSV->isNullMemberPointer())
1095         return UndefinedVal();
1096       if (const FieldDecl *FD = PTMSV->getDeclAs<FieldDecl>()) {
1097         SVal Result = lhs;
1098 
1099         for (const auto &I : *PTMSV)
1100           Result = StateMgr.getStoreManager().evalDerivedToBase(
1101               Result, I->getType(),I->isVirtual());
1102         return state->getLValue(FD, Result);
1103       }
1104     }
1105 
1106     return rhs;
1107   }
1108 
1109   assert(!BinaryOperator::isComparisonOp(op) &&
1110          "arguments to comparison ops must be of the same type");
1111 
1112   // Special case: rhs is a zero constant.
1113   if (rhs.isZeroConstant())
1114     return lhs;
1115 
1116   // Perserve the null pointer so that it can be found by the DerefChecker.
1117   if (lhs.isZeroConstant())
1118     return lhs;
1119 
1120   // We are dealing with pointer arithmetic.
1121 
1122   // Handle pointer arithmetic on constant values.
1123   if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
1124     if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
1125       const llvm::APSInt &leftI = lhsInt->getValue();
1126       assert(leftI.isUnsigned());
1127       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1128 
1129       // Convert the bitwidth of rightI.  This should deal with overflow
1130       // since we are dealing with concrete values.
1131       rightI = rightI.extOrTrunc(leftI.getBitWidth());
1132 
1133       // Offset the increment by the pointer size.
1134       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
1135       QualType pointeeType = resultTy->getPointeeType();
1136       Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1137       rightI *= Multiplicand;
1138 
1139       // Compute the adjusted pointer.
1140       switch (op) {
1141         case BO_Add:
1142           rightI = leftI + rightI;
1143           break;
1144         case BO_Sub:
1145           rightI = leftI - rightI;
1146           break;
1147         default:
1148           llvm_unreachable("Invalid pointer arithmetic operation");
1149       }
1150       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1151     }
1152   }
1153 
1154   // Handle cases where 'lhs' is a region.
1155   if (const MemRegion *region = lhs.getAsRegion()) {
1156     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1157     SVal index = UnknownVal();
1158     const SubRegion *superR = nullptr;
1159     // We need to know the type of the pointer in order to add an integer to it.
1160     // Depending on the type, different amount of bytes is added.
1161     QualType elementType;
1162 
1163     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
1164       assert(op == BO_Add || op == BO_Sub);
1165       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1166                           getArrayIndexType());
1167       superR = cast<SubRegion>(elemReg->getSuperRegion());
1168       elementType = elemReg->getElementType();
1169     }
1170     else if (isa<SubRegion>(region)) {
1171       assert(op == BO_Add || op == BO_Sub);
1172       index = (op == BO_Add) ? rhs : evalMinus(rhs);
1173       superR = cast<SubRegion>(region);
1174       // TODO: Is this actually reliable? Maybe improving our MemRegion
1175       // hierarchy to provide typed regions for all non-void pointers would be
1176       // better. For instance, we cannot extend this towards LocAsInteger
1177       // operations, where result type of the expression is integer.
1178       if (resultTy->isAnyPointerType())
1179         elementType = resultTy->getPointeeType();
1180     }
1181 
1182     // Represent arithmetic on void pointers as arithmetic on char pointers.
1183     // It is fine when a TypedValueRegion of char value type represents
1184     // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1185     if (elementType->isVoidType())
1186       elementType = getContext().CharTy;
1187 
1188     if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1189       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1190                                                        superR, getContext()));
1191     }
1192   }
1193   return UnknownVal();
1194 }
1195 
1196 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1197                                                    SVal V) {
1198   if (V.isUnknownOrUndef())
1199     return nullptr;
1200 
1201   if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1202     return &X->getValue();
1203 
1204   if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1205     return &X->getValue();
1206 
1207   if (SymbolRef Sym = V.getAsSymbol())
1208     return state->getConstraintManager().getSymVal(state, Sym);
1209 
1210   // FIXME: Add support for SymExprs.
1211   return nullptr;
1212 }
1213 
1214 SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
1215   // For now, this function tries to constant-fold symbols inside a
1216   // nonloc::SymbolVal, and does nothing else. More simplifications should
1217   // be possible, such as constant-folding an index in an ElementRegion.
1218 
1219   class Simplifier : public FullSValVisitor<Simplifier, SVal> {
1220     ProgramStateRef State;
1221     SValBuilder &SVB;
1222 
1223   public:
1224     Simplifier(ProgramStateRef State)
1225         : State(State), SVB(State->getStateManager().getSValBuilder()) {}
1226 
1227     SVal VisitSymbolData(const SymbolData *S) {
1228       if (const llvm::APSInt *I =
1229               SVB.getKnownValue(State, nonloc::SymbolVal(S)))
1230         return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
1231                                             : (SVal)SVB.makeIntVal(*I);
1232       return Loc::isLocType(S->getType()) ? (SVal)SVB.makeLoc(S)
1233                                           : nonloc::SymbolVal(S);
1234     }
1235 
1236     // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
1237     // start producing them.
1238 
1239     SVal VisitSymIntExpr(const SymIntExpr *S) {
1240       SVal LHS = Visit(S->getLHS());
1241       SVal RHS;
1242       // By looking at the APSInt in the right-hand side of S, we cannot
1243       // figure out if it should be treated as a Loc or as a NonLoc.
1244       // So make our guess by recalling that we cannot multiply pointers
1245       // or compare a pointer to an integer.
1246       if (Loc::isLocType(S->getLHS()->getType()) &&
1247           BinaryOperator::isComparisonOp(S->getOpcode())) {
1248         // The usual conversion of $sym to &SymRegion{$sym}, as they have
1249         // the same meaning for Loc-type symbols, but the latter form
1250         // is preferred in SVal computations for being Loc itself.
1251         if (SymbolRef Sym = LHS.getAsSymbol()) {
1252           assert(Loc::isLocType(Sym->getType()));
1253           LHS = SVB.makeLoc(Sym);
1254         }
1255         RHS = SVB.makeIntLocVal(S->getRHS());
1256       } else {
1257         RHS = SVB.makeIntVal(S->getRHS());
1258       }
1259       return SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType());
1260     }
1261 
1262     SVal VisitSymSymExpr(const SymSymExpr *S) {
1263       SVal LHS = Visit(S->getLHS());
1264       SVal RHS = Visit(S->getRHS());
1265       return SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType());
1266     }
1267 
1268     SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
1269 
1270     SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
1271 
1272     SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
1273       // Simplification is much more costly than computing complexity.
1274       // For high complexity, it may be not worth it.
1275       if (V.getSymbol()->computeComplexity() > 100)
1276         return V;
1277       return Visit(V.getSymbol());
1278     }
1279 
1280     SVal VisitSVal(SVal V) { return V; }
1281   };
1282 
1283   return Simplifier(State).Visit(V);
1284 }
1285