1 // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
14 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
19 
20 using namespace clang;
21 using namespace ento;
22 
23 namespace {
24 class SimpleSValBuilder : public SValBuilder {
25 protected:
26   SVal dispatchCast(SVal val, QualType castTy) override;
27   SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
28   SVal evalCastFromLoc(Loc val, QualType castTy) override;
29 
30 public:
31   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
32                     ProgramStateManager &stateMgr)
33                     : SValBuilder(alloc, context, stateMgr) {}
34   ~SimpleSValBuilder() override {}
35 
36   SVal evalMinus(NonLoc val) override;
37   SVal evalComplement(NonLoc val) override;
38   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
39                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
40   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
41                    Loc lhs, Loc rhs, QualType resultTy) override;
42   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
43                    Loc lhs, NonLoc rhs, QualType resultTy) override;
44 
45   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
46   ///  (integer) value, that value is returned. Otherwise, returns NULL.
47   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
48 
49   /// Recursively descends into symbolic expressions and replaces symbols
50   /// with their known values (in the sense of the getKnownValue() method).
51   SVal simplifySVal(ProgramStateRef State, SVal V) override;
52 
53   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
54                      const llvm::APSInt &RHS, QualType resultTy);
55 };
56 } // end anonymous namespace
57 
58 SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
59                                            ASTContext &context,
60                                            ProgramStateManager &stateMgr) {
61   return new SimpleSValBuilder(alloc, context, stateMgr);
62 }
63 
64 //===----------------------------------------------------------------------===//
65 // Transfer function for Casts.
66 //===----------------------------------------------------------------------===//
67 
68 SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
69   assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
70   return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
71                            : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
72 }
73 
74 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
75   bool isLocType = Loc::isLocType(castTy);
76   if (val.getAs<nonloc::PointerToMember>())
77     return val;
78 
79   if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
80     if (isLocType)
81       return LI->getLoc();
82     // FIXME: Correctly support promotions/truncations.
83     unsigned castSize = Context.getIntWidth(castTy);
84     if (castSize == LI->getNumBits())
85       return val;
86     return makeLocAsInteger(LI->getLoc(), castSize);
87   }
88 
89   if (SymbolRef se = val.getAsSymbol()) {
90     QualType T = Context.getCanonicalType(se->getType());
91     // If types are the same or both are integers, ignore the cast.
92     // FIXME: Remove this hack when we support symbolic truncation/extension.
93     // HACK: If both castTy and T are integers, ignore the cast.  This is
94     // not a permanent solution.  Eventually we want to precisely handle
95     // extension/truncation of symbolic integers.  This prevents us from losing
96     // precision when we assign 'x = y' and 'y' is symbolic and x and y are
97     // different integer types.
98    if (haveSameType(T, castTy))
99       return val;
100 
101     if (!isLocType)
102       return makeNonLoc(se, T, castTy);
103     return UnknownVal();
104   }
105 
106   // If value is a non-integer constant, produce unknown.
107   if (!val.getAs<nonloc::ConcreteInt>())
108     return UnknownVal();
109 
110   // Handle casts to a boolean type.
111   if (castTy->isBooleanType()) {
112     bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
113     return makeTruthVal(b, castTy);
114   }
115 
116   // Only handle casts from integers to integers - if val is an integer constant
117   // being cast to a non-integer type, produce unknown.
118   if (!isLocType && !castTy->isIntegralOrEnumerationType())
119     return UnknownVal();
120 
121   llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
122   BasicVals.getAPSIntType(castTy).apply(i);
123 
124   if (isLocType)
125     return makeIntLocVal(i);
126   else
127     return makeIntVal(i);
128 }
129 
130 SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
131 
132   // Casts from pointers -> pointers, just return the lval.
133   //
134   // Casts from pointers -> references, just return the lval.  These
135   //   can be introduced by the frontend for corner cases, e.g
136   //   casting from va_list* to __builtin_va_list&.
137   //
138   if (Loc::isLocType(castTy) || castTy->isReferenceType())
139     return val;
140 
141   // FIXME: Handle transparent unions where a value can be "transparently"
142   //  lifted into a union type.
143   if (castTy->isUnionType())
144     return UnknownVal();
145 
146   // Casting a Loc to a bool will almost always be true,
147   // unless this is a weak function or a symbolic region.
148   if (castTy->isBooleanType()) {
149     switch (val.getSubKind()) {
150       case loc::MemRegionValKind: {
151         const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
152         if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
153           if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
154             if (FD->isWeak())
155               // FIXME: Currently we are using an extent symbol here,
156               // because there are no generic region address metadata
157               // symbols to use, only content metadata.
158               return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
159 
160         if (const SymbolicRegion *SymR = R->getSymbolicBase())
161           return makeNonLoc(SymR->getSymbol(), BO_NE,
162                             BasicVals.getZeroWithPtrWidth(), castTy);
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   // FIXME: After putting complexity threshold to the symbols we can always
459   //        rearrange additive operations but rearrange comparisons only if
460   //        option is set.
461   if(!Opts.ShouldAggressivelySimplifyBinaryOperation)
462     return None;
463 
464   SymbolRef LSym = Lhs.getAsSymbol();
465   if (!LSym)
466     return None;
467 
468   if (BinaryOperator::isComparisonOp(Op)) {
469     SingleTy = LSym->getType();
470     if (ResultTy != SVB.getConditionType())
471       return None;
472     // Initialize SingleTy later with a symbol's type.
473   } else if (BinaryOperator::isAdditiveOp(Op)) {
474     SingleTy = ResultTy;
475     if (LSym->getType() != SingleTy)
476       return None;
477   } else {
478     // Don't rearrange other operations.
479     return None;
480   }
481 
482   assert(!SingleTy.isNull() && "We should have figured out the type by now!");
483 
484   // Rearrange signed symbolic expressions only
485   if (!SingleTy->isSignedIntegerOrEnumerationType())
486     return None;
487 
488   SymbolRef RSym = Rhs.getAsSymbol();
489   if (!RSym || RSym->getType() != SingleTy)
490     return None;
491 
492   BasicValueFactory &BV = State->getBasicVals();
493   llvm::APSInt LInt, RInt;
494   std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
495   std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
496   if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
497       !shouldRearrange(State, Op, RSym, RInt, SingleTy))
498     return None;
499 
500   // We know that no overflows can occur anymore.
501   return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
502 }
503 
504 SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
505                                   BinaryOperator::Opcode op,
506                                   NonLoc lhs, NonLoc rhs,
507                                   QualType resultTy)  {
508   NonLoc InputLHS = lhs;
509   NonLoc InputRHS = rhs;
510 
511   // Handle trivial case where left-side and right-side are the same.
512   if (lhs == rhs)
513     switch (op) {
514       default:
515         break;
516       case BO_EQ:
517       case BO_LE:
518       case BO_GE:
519         return makeTruthVal(true, resultTy);
520       case BO_LT:
521       case BO_GT:
522       case BO_NE:
523         return makeTruthVal(false, resultTy);
524       case BO_Xor:
525       case BO_Sub:
526         if (resultTy->isIntegralOrEnumerationType())
527           return makeIntVal(0, resultTy);
528         return evalCastFromNonLoc(makeIntVal(0, /*isUnsigned=*/false), resultTy);
529       case BO_Or:
530       case BO_And:
531         return evalCastFromNonLoc(lhs, resultTy);
532     }
533 
534   while (1) {
535     switch (lhs.getSubKind()) {
536     default:
537       return makeSymExprValNN(op, lhs, rhs, resultTy);
538     case nonloc::PointerToMemberKind: {
539       assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
540              "Both SVals should have pointer-to-member-type");
541       auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
542            RPTM = rhs.castAs<nonloc::PointerToMember>();
543       auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
544       switch (op) {
545         case BO_EQ:
546           return makeTruthVal(LPTMD == RPTMD, resultTy);
547         case BO_NE:
548           return makeTruthVal(LPTMD != RPTMD, resultTy);
549         default:
550           return UnknownVal();
551       }
552     }
553     case nonloc::LocAsIntegerKind: {
554       Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
555       switch (rhs.getSubKind()) {
556         case nonloc::LocAsIntegerKind:
557           // FIXME: at the moment the implementation
558           // of modeling "pointers as integers" is not complete.
559           if (!BinaryOperator::isComparisonOp(op))
560             return UnknownVal();
561           return evalBinOpLL(state, op, lhsL,
562                              rhs.castAs<nonloc::LocAsInteger>().getLoc(),
563                              resultTy);
564         case nonloc::ConcreteIntKind: {
565           // FIXME: at the moment the implementation
566           // of modeling "pointers as integers" is not complete.
567           if (!BinaryOperator::isComparisonOp(op))
568             return UnknownVal();
569           // Transform the integer into a location and compare.
570           // FIXME: This only makes sense for comparisons. If we want to, say,
571           // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
572           // then pack it back into a LocAsInteger.
573           llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
574           // If the region has a symbolic base, pay attention to the type; it
575           // might be coming from a non-default address space. For non-symbolic
576           // regions it doesn't matter that much because such comparisons would
577           // most likely evaluate to concrete false anyway. FIXME: We might
578           // still need to handle the non-comparison case.
579           if (SymbolRef lSym = lhs.getAsLocSymbol(true))
580             BasicVals.getAPSIntType(lSym->getType()).apply(i);
581           else
582             BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
583           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
584         }
585         default:
586           switch (op) {
587             case BO_EQ:
588               return makeTruthVal(false, resultTy);
589             case BO_NE:
590               return makeTruthVal(true, resultTy);
591             default:
592               // This case also handles pointer arithmetic.
593               return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
594           }
595       }
596     }
597     case nonloc::ConcreteIntKind: {
598       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
599 
600       // If we're dealing with two known constants, just perform the operation.
601       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
602         llvm::APSInt RHSValue = *KnownRHSValue;
603         if (BinaryOperator::isComparisonOp(op)) {
604           // We're looking for a type big enough to compare the two values.
605           // FIXME: This is not correct. char + short will result in a promotion
606           // to int. Unfortunately we have lost types by this point.
607           APSIntType CompareType = std::max(APSIntType(LHSValue),
608                                             APSIntType(RHSValue));
609           CompareType.apply(LHSValue);
610           CompareType.apply(RHSValue);
611         } else if (!BinaryOperator::isShiftOp(op)) {
612           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
613           IntType.apply(LHSValue);
614           IntType.apply(RHSValue);
615         }
616 
617         const llvm::APSInt *Result =
618           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
619         if (!Result)
620           return UndefinedVal();
621 
622         return nonloc::ConcreteInt(*Result);
623       }
624 
625       // Swap the left and right sides and flip the operator if doing so
626       // allows us to better reason about the expression (this is a form
627       // of expression canonicalization).
628       // While we're at it, catch some special cases for non-commutative ops.
629       switch (op) {
630       case BO_LT:
631       case BO_GT:
632       case BO_LE:
633       case BO_GE:
634         op = BinaryOperator::reverseComparisonOp(op);
635         LLVM_FALLTHROUGH;
636       case BO_EQ:
637       case BO_NE:
638       case BO_Add:
639       case BO_Mul:
640       case BO_And:
641       case BO_Xor:
642       case BO_Or:
643         std::swap(lhs, rhs);
644         continue;
645       case BO_Shr:
646         // (~0)>>a
647         if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
648           return evalCastFromNonLoc(lhs, resultTy);
649         LLVM_FALLTHROUGH;
650       case BO_Shl:
651         // 0<<a and 0>>a
652         if (LHSValue == 0)
653           return evalCastFromNonLoc(lhs, resultTy);
654         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
655       case BO_Div:
656         // 0 / x == 0
657       case BO_Rem:
658         // 0 % x == 0
659         if (LHSValue == 0)
660           return makeZeroVal(resultTy);
661         LLVM_FALLTHROUGH;
662       default:
663         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
664       }
665     }
666     case nonloc::SymbolValKind: {
667       // We only handle LHS as simple symbols or SymIntExprs.
668       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
669 
670       // LHS is a symbolic expression.
671       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
672 
673         // Is this a logical not? (!x is represented as x == 0.)
674         if (op == BO_EQ && rhs.isZeroConstant()) {
675           // We know how to negate certain expressions. Simplify them here.
676 
677           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
678           switch (opc) {
679           default:
680             // We don't know how to negate this operation.
681             // Just handle it as if it were a normal comparison to 0.
682             break;
683           case BO_LAnd:
684           case BO_LOr:
685             llvm_unreachable("Logical operators handled by branching logic.");
686           case BO_Assign:
687           case BO_MulAssign:
688           case BO_DivAssign:
689           case BO_RemAssign:
690           case BO_AddAssign:
691           case BO_SubAssign:
692           case BO_ShlAssign:
693           case BO_ShrAssign:
694           case BO_AndAssign:
695           case BO_XorAssign:
696           case BO_OrAssign:
697           case BO_Comma:
698             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
699           case BO_PtrMemD:
700           case BO_PtrMemI:
701             llvm_unreachable("Pointer arithmetic not handled here.");
702           case BO_LT:
703           case BO_GT:
704           case BO_LE:
705           case BO_GE:
706           case BO_EQ:
707           case BO_NE:
708             assert(resultTy->isBooleanType() ||
709                    resultTy == getConditionType());
710             assert(symIntExpr->getType()->isBooleanType() ||
711                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
712                                                        getConditionType()));
713             // Negate the comparison and make a value.
714             opc = BinaryOperator::negateComparisonOp(opc);
715             return makeNonLoc(symIntExpr->getLHS(), opc,
716                 symIntExpr->getRHS(), resultTy);
717           }
718         }
719 
720         // For now, only handle expressions whose RHS is a constant.
721         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
722           // If both the LHS and the current expression are additive,
723           // fold their constants and try again.
724           if (BinaryOperator::isAdditiveOp(op)) {
725             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
726             if (BinaryOperator::isAdditiveOp(lop)) {
727               // Convert the two constants to a common type, then combine them.
728 
729               // resultTy may not be the best type to convert to, but it's
730               // probably the best choice in expressions with mixed type
731               // (such as x+1U+2LL). The rules for implicit conversions should
732               // choose a reasonable type to preserve the expression, and will
733               // at least match how the value is going to be used.
734               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
735               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
736               const llvm::APSInt &second = IntType.convert(*RHSValue);
737 
738               const llvm::APSInt *newRHS;
739               if (lop == op)
740                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
741               else
742                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
743 
744               assert(newRHS && "Invalid operation despite common type!");
745               rhs = nonloc::ConcreteInt(*newRHS);
746               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
747               op = lop;
748               continue;
749             }
750           }
751 
752           // Otherwise, make a SymIntExpr out of the expression.
753           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
754         }
755       }
756 
757       // Does the symbolic expression simplify to a constant?
758       // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
759       // and try again.
760       SVal simplifiedLhs = simplifySVal(state, lhs);
761       if (simplifiedLhs != lhs)
762         if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
763           lhs = *simplifiedLhsAsNonLoc;
764           continue;
765         }
766 
767       // Is the RHS a constant?
768       if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
769         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
770 
771       if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
772         return *V;
773 
774       // Give up -- this is not a symbolic expression we can handle.
775       return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
776     }
777     }
778   }
779 }
780 
781 static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
782                                             const FieldRegion *RightFR,
783                                             BinaryOperator::Opcode op,
784                                             QualType resultTy,
785                                             SimpleSValBuilder &SVB) {
786   // Only comparisons are meaningful here!
787   if (!BinaryOperator::isComparisonOp(op))
788     return UnknownVal();
789 
790   // Next, see if the two FRs have the same super-region.
791   // FIXME: This doesn't handle casts yet, and simply stripping the casts
792   // doesn't help.
793   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
794     return UnknownVal();
795 
796   const FieldDecl *LeftFD = LeftFR->getDecl();
797   const FieldDecl *RightFD = RightFR->getDecl();
798   const RecordDecl *RD = LeftFD->getParent();
799 
800   // Make sure the two FRs are from the same kind of record. Just in case!
801   // FIXME: This is probably where inheritance would be a problem.
802   if (RD != RightFD->getParent())
803     return UnknownVal();
804 
805   // We know for sure that the two fields are not the same, since that
806   // would have given us the same SVal.
807   if (op == BO_EQ)
808     return SVB.makeTruthVal(false, resultTy);
809   if (op == BO_NE)
810     return SVB.makeTruthVal(true, resultTy);
811 
812   // Iterate through the fields and see which one comes first.
813   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
814   // members and the units in which bit-fields reside have addresses that
815   // increase in the order in which they are declared."
816   bool leftFirst = (op == BO_LT || op == BO_LE);
817   for (const auto *I : RD->fields()) {
818     if (I == LeftFD)
819       return SVB.makeTruthVal(leftFirst, resultTy);
820     if (I == RightFD)
821       return SVB.makeTruthVal(!leftFirst, resultTy);
822   }
823 
824   llvm_unreachable("Fields not found in parent record's definition");
825 }
826 
827 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
828 SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
829                                   BinaryOperator::Opcode op,
830                                   Loc lhs, Loc rhs,
831                                   QualType resultTy) {
832   // Only comparisons and subtractions are valid operations on two pointers.
833   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
834   // However, if a pointer is casted to an integer, evalBinOpNN may end up
835   // calling this function with another operation (PR7527). We don't attempt to
836   // model this for now, but it could be useful, particularly when the
837   // "location" is actually an integer value that's been passed through a void*.
838   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
839     return UnknownVal();
840 
841   // Special cases for when both sides are identical.
842   if (lhs == rhs) {
843     switch (op) {
844     default:
845       llvm_unreachable("Unimplemented operation for two identical values");
846     case BO_Sub:
847       return makeZeroVal(resultTy);
848     case BO_EQ:
849     case BO_LE:
850     case BO_GE:
851       return makeTruthVal(true, resultTy);
852     case BO_NE:
853     case BO_LT:
854     case BO_GT:
855       return makeTruthVal(false, resultTy);
856     }
857   }
858 
859   switch (lhs.getSubKind()) {
860   default:
861     llvm_unreachable("Ordering not implemented for this Loc.");
862 
863   case loc::GotoLabelKind:
864     // The only thing we know about labels is that they're non-null.
865     if (rhs.isZeroConstant()) {
866       switch (op) {
867       default:
868         break;
869       case BO_Sub:
870         return evalCastFromLoc(lhs, resultTy);
871       case BO_EQ:
872       case BO_LE:
873       case BO_LT:
874         return makeTruthVal(false, resultTy);
875       case BO_NE:
876       case BO_GT:
877       case BO_GE:
878         return makeTruthVal(true, resultTy);
879       }
880     }
881     // There may be two labels for the same location, and a function region may
882     // have the same address as a label at the start of the function (depending
883     // on the ABI).
884     // FIXME: we can probably do a comparison against other MemRegions, though.
885     // FIXME: is there a way to tell if two labels refer to the same location?
886     return UnknownVal();
887 
888   case loc::ConcreteIntKind: {
889     // If one of the operands is a symbol and the other is a constant,
890     // build an expression for use by the constraint manager.
891     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
892       // We can only build expressions with symbols on the left,
893       // so we need a reversible operator.
894       if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
895         return UnknownVal();
896 
897       const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
898       op = BinaryOperator::reverseComparisonOp(op);
899       return makeNonLoc(rSym, op, lVal, resultTy);
900     }
901 
902     // If both operands are constants, just perform the operation.
903     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
904       SVal ResultVal =
905           lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
906       if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
907         return evalCastFromNonLoc(*Result, resultTy);
908 
909       assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
910       return UnknownVal();
911     }
912 
913     // Special case comparisons against NULL.
914     // This must come after the test if the RHS is a symbol, which is used to
915     // build constraints. The address of any non-symbolic region is guaranteed
916     // to be non-NULL, as is any label.
917     assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
918     if (lhs.isZeroConstant()) {
919       switch (op) {
920       default:
921         break;
922       case BO_EQ:
923       case BO_GT:
924       case BO_GE:
925         return makeTruthVal(false, resultTy);
926       case BO_NE:
927       case BO_LT:
928       case BO_LE:
929         return makeTruthVal(true, resultTy);
930       }
931     }
932 
933     // Comparing an arbitrary integer to a region or label address is
934     // completely unknowable.
935     return UnknownVal();
936   }
937   case loc::MemRegionValKind: {
938     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
939       // If one of the operands is a symbol and the other is a constant,
940       // build an expression for use by the constraint manager.
941       if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
942         if (BinaryOperator::isComparisonOp(op))
943           return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
944         return UnknownVal();
945       }
946       // Special case comparisons to NULL.
947       // This must come after the test if the LHS is a symbol, which is used to
948       // build constraints. The address of any non-symbolic region is guaranteed
949       // to be non-NULL.
950       if (rInt->isZeroConstant()) {
951         if (op == BO_Sub)
952           return evalCastFromLoc(lhs, resultTy);
953 
954         if (BinaryOperator::isComparisonOp(op)) {
955           QualType boolType = getContext().BoolTy;
956           NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
957           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
958           return evalBinOpNN(state, op, l, r, resultTy);
959         }
960       }
961 
962       // Comparing a region to an arbitrary integer is completely unknowable.
963       return UnknownVal();
964     }
965 
966     // Get both values as regions, if possible.
967     const MemRegion *LeftMR = lhs.getAsRegion();
968     assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
969 
970     const MemRegion *RightMR = rhs.getAsRegion();
971     if (!RightMR)
972       // The RHS is probably a label, which in theory could address a region.
973       // FIXME: we can probably make a more useful statement about non-code
974       // regions, though.
975       return UnknownVal();
976 
977     const MemRegion *LeftBase = LeftMR->getBaseRegion();
978     const MemRegion *RightBase = RightMR->getBaseRegion();
979     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
980     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
981     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
982 
983     // If the two regions are from different known memory spaces they cannot be
984     // equal. Also, assume that no symbolic region (whose memory space is
985     // unknown) is on the stack.
986     if (LeftMS != RightMS &&
987         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
988          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
989       switch (op) {
990       default:
991         return UnknownVal();
992       case BO_EQ:
993         return makeTruthVal(false, resultTy);
994       case BO_NE:
995         return makeTruthVal(true, resultTy);
996       }
997     }
998 
999     // If both values wrap regions, see if they're from different base regions.
1000     // Note, heap base symbolic regions are assumed to not alias with
1001     // each other; for example, we assume that malloc returns different address
1002     // on each invocation.
1003     // FIXME: ObjC object pointers always reside on the heap, but currently
1004     // we treat their memory space as unknown, because symbolic pointers
1005     // to ObjC objects may alias. There should be a way to construct
1006     // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
1007     // guesses memory space for ObjC object pointers manually instead of
1008     // relying on us.
1009     if (LeftBase != RightBase &&
1010         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
1011          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
1012       switch (op) {
1013       default:
1014         return UnknownVal();
1015       case BO_EQ:
1016         return makeTruthVal(false, resultTy);
1017       case BO_NE:
1018         return makeTruthVal(true, resultTy);
1019       }
1020     }
1021 
1022     // Handle special cases for when both regions are element regions.
1023     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
1024     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
1025     if (RightER && LeftER) {
1026       // Next, see if the two ERs have the same super-region and matching types.
1027       // FIXME: This should do something useful even if the types don't match,
1028       // though if both indexes are constant the RegionRawOffset path will
1029       // give the correct answer.
1030       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
1031           LeftER->getElementType() == RightER->getElementType()) {
1032         // Get the left index and cast it to the correct type.
1033         // If the index is unknown or undefined, bail out here.
1034         SVal LeftIndexVal = LeftER->getIndex();
1035         Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
1036         if (!LeftIndex)
1037           return UnknownVal();
1038         LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
1039         LeftIndex = LeftIndexVal.getAs<NonLoc>();
1040         if (!LeftIndex)
1041           return UnknownVal();
1042 
1043         // Do the same for the right index.
1044         SVal RightIndexVal = RightER->getIndex();
1045         Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
1046         if (!RightIndex)
1047           return UnknownVal();
1048         RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
1049         RightIndex = RightIndexVal.getAs<NonLoc>();
1050         if (!RightIndex)
1051           return UnknownVal();
1052 
1053         // Actually perform the operation.
1054         // evalBinOpNN expects the two indexes to already be the right type.
1055         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
1056       }
1057     }
1058 
1059     // Special handling of the FieldRegions, even with symbolic offsets.
1060     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
1061     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
1062     if (RightFR && LeftFR) {
1063       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
1064                                                *this);
1065       if (!R.isUnknown())
1066         return R;
1067     }
1068 
1069     // Compare the regions using the raw offsets.
1070     RegionOffset LeftOffset = LeftMR->getAsOffset();
1071     RegionOffset RightOffset = RightMR->getAsOffset();
1072 
1073     if (LeftOffset.getRegion() != nullptr &&
1074         LeftOffset.getRegion() == RightOffset.getRegion() &&
1075         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
1076       int64_t left = LeftOffset.getOffset();
1077       int64_t right = RightOffset.getOffset();
1078 
1079       switch (op) {
1080         default:
1081           return UnknownVal();
1082         case BO_LT:
1083           return makeTruthVal(left < right, resultTy);
1084         case BO_GT:
1085           return makeTruthVal(left > right, resultTy);
1086         case BO_LE:
1087           return makeTruthVal(left <= right, resultTy);
1088         case BO_GE:
1089           return makeTruthVal(left >= right, resultTy);
1090         case BO_EQ:
1091           return makeTruthVal(left == right, resultTy);
1092         case BO_NE:
1093           return makeTruthVal(left != right, resultTy);
1094       }
1095     }
1096 
1097     // At this point we're not going to get a good answer, but we can try
1098     // conjuring an expression instead.
1099     SymbolRef LHSSym = lhs.getAsLocSymbol();
1100     SymbolRef RHSSym = rhs.getAsLocSymbol();
1101     if (LHSSym && RHSSym)
1102       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
1103 
1104     // If we get here, we have no way of comparing the regions.
1105     return UnknownVal();
1106   }
1107   }
1108 }
1109 
1110 SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
1111                                     BinaryOperator::Opcode op, Loc lhs,
1112                                     NonLoc rhs, QualType resultTy) {
1113   if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
1114     if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
1115       if (PTMSV->isNullMemberPointer())
1116         return UndefinedVal();
1117 
1118       auto getFieldLValue = [&](const auto *FD) -> SVal {
1119         SVal Result = lhs;
1120 
1121         for (const auto &I : *PTMSV)
1122           Result = StateMgr.getStoreManager().evalDerivedToBase(
1123               Result, I->getType(), I->isVirtual());
1124 
1125         return state->getLValue(FD, Result);
1126       };
1127 
1128       if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) {
1129         return getFieldLValue(FD);
1130       }
1131       if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) {
1132         return getFieldLValue(FD);
1133       }
1134     }
1135 
1136     return rhs;
1137   }
1138 
1139   assert(!BinaryOperator::isComparisonOp(op) &&
1140          "arguments to comparison ops must be of the same type");
1141 
1142   // Special case: rhs is a zero constant.
1143   if (rhs.isZeroConstant())
1144     return lhs;
1145 
1146   // Perserve the null pointer so that it can be found by the DerefChecker.
1147   if (lhs.isZeroConstant())
1148     return lhs;
1149 
1150   // We are dealing with pointer arithmetic.
1151 
1152   // Handle pointer arithmetic on constant values.
1153   if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
1154     if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
1155       const llvm::APSInt &leftI = lhsInt->getValue();
1156       assert(leftI.isUnsigned());
1157       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1158 
1159       // Convert the bitwidth of rightI.  This should deal with overflow
1160       // since we are dealing with concrete values.
1161       rightI = rightI.extOrTrunc(leftI.getBitWidth());
1162 
1163       // Offset the increment by the pointer size.
1164       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
1165       QualType pointeeType = resultTy->getPointeeType();
1166       Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1167       rightI *= Multiplicand;
1168 
1169       // Compute the adjusted pointer.
1170       switch (op) {
1171         case BO_Add:
1172           rightI = leftI + rightI;
1173           break;
1174         case BO_Sub:
1175           rightI = leftI - rightI;
1176           break;
1177         default:
1178           llvm_unreachable("Invalid pointer arithmetic operation");
1179       }
1180       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1181     }
1182   }
1183 
1184   // Handle cases where 'lhs' is a region.
1185   if (const MemRegion *region = lhs.getAsRegion()) {
1186     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1187     SVal index = UnknownVal();
1188     const SubRegion *superR = nullptr;
1189     // We need to know the type of the pointer in order to add an integer to it.
1190     // Depending on the type, different amount of bytes is added.
1191     QualType elementType;
1192 
1193     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
1194       assert(op == BO_Add || op == BO_Sub);
1195       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1196                           getArrayIndexType());
1197       superR = cast<SubRegion>(elemReg->getSuperRegion());
1198       elementType = elemReg->getElementType();
1199     }
1200     else if (isa<SubRegion>(region)) {
1201       assert(op == BO_Add || op == BO_Sub);
1202       index = (op == BO_Add) ? rhs : evalMinus(rhs);
1203       superR = cast<SubRegion>(region);
1204       // TODO: Is this actually reliable? Maybe improving our MemRegion
1205       // hierarchy to provide typed regions for all non-void pointers would be
1206       // better. For instance, we cannot extend this towards LocAsInteger
1207       // operations, where result type of the expression is integer.
1208       if (resultTy->isAnyPointerType())
1209         elementType = resultTy->getPointeeType();
1210     }
1211 
1212     // Represent arithmetic on void pointers as arithmetic on char pointers.
1213     // It is fine when a TypedValueRegion of char value type represents
1214     // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1215     if (elementType->isVoidType())
1216       elementType = getContext().CharTy;
1217 
1218     if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1219       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1220                                                        superR, getContext()));
1221     }
1222   }
1223   return UnknownVal();
1224 }
1225 
1226 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1227                                                    SVal V) {
1228   V = simplifySVal(state, V);
1229   if (V.isUnknownOrUndef())
1230     return nullptr;
1231 
1232   if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1233     return &X->getValue();
1234 
1235   if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1236     return &X->getValue();
1237 
1238   if (SymbolRef Sym = V.getAsSymbol())
1239     return state->getConstraintManager().getSymVal(state, Sym);
1240 
1241   // FIXME: Add support for SymExprs.
1242   return nullptr;
1243 }
1244 
1245 SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
1246   // For now, this function tries to constant-fold symbols inside a
1247   // nonloc::SymbolVal, and does nothing else. More simplifications should
1248   // be possible, such as constant-folding an index in an ElementRegion.
1249 
1250   class Simplifier : public FullSValVisitor<Simplifier, SVal> {
1251     ProgramStateRef State;
1252     SValBuilder &SVB;
1253 
1254     // Cache results for the lifetime of the Simplifier. Results change every
1255     // time new constraints are added to the program state, which is the whole
1256     // point of simplifying, and for that very reason it's pointless to maintain
1257     // the same cache for the duration of the whole analysis.
1258     llvm::DenseMap<SymbolRef, SVal> Cached;
1259 
1260     static bool isUnchanged(SymbolRef Sym, SVal Val) {
1261       return Sym == Val.getAsSymbol();
1262     }
1263 
1264     SVal cache(SymbolRef Sym, SVal V) {
1265       Cached[Sym] = V;
1266       return V;
1267     }
1268 
1269     SVal skip(SymbolRef Sym) {
1270       return cache(Sym, SVB.makeSymbolVal(Sym));
1271     }
1272 
1273   public:
1274     Simplifier(ProgramStateRef State)
1275         : State(State), SVB(State->getStateManager().getSValBuilder()) {}
1276 
1277     SVal VisitSymbolData(const SymbolData *S) {
1278       // No cache here.
1279       if (const llvm::APSInt *I =
1280               SVB.getKnownValue(State, SVB.makeSymbolVal(S)))
1281         return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
1282                                             : (SVal)SVB.makeIntVal(*I);
1283       return SVB.makeSymbolVal(S);
1284     }
1285 
1286     // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
1287     // start producing them.
1288 
1289     SVal VisitSymIntExpr(const SymIntExpr *S) {
1290       auto I = Cached.find(S);
1291       if (I != Cached.end())
1292         return I->second;
1293 
1294       SVal LHS = Visit(S->getLHS());
1295       if (isUnchanged(S->getLHS(), LHS))
1296         return skip(S);
1297 
1298       SVal RHS;
1299       // By looking at the APSInt in the right-hand side of S, we cannot
1300       // figure out if it should be treated as a Loc or as a NonLoc.
1301       // So make our guess by recalling that we cannot multiply pointers
1302       // or compare a pointer to an integer.
1303       if (Loc::isLocType(S->getLHS()->getType()) &&
1304           BinaryOperator::isComparisonOp(S->getOpcode())) {
1305         // The usual conversion of $sym to &SymRegion{$sym}, as they have
1306         // the same meaning for Loc-type symbols, but the latter form
1307         // is preferred in SVal computations for being Loc itself.
1308         if (SymbolRef Sym = LHS.getAsSymbol()) {
1309           assert(Loc::isLocType(Sym->getType()));
1310           LHS = SVB.makeLoc(Sym);
1311         }
1312         RHS = SVB.makeIntLocVal(S->getRHS());
1313       } else {
1314         RHS = SVB.makeIntVal(S->getRHS());
1315       }
1316 
1317       return cache(
1318           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1319     }
1320 
1321     SVal VisitSymSymExpr(const SymSymExpr *S) {
1322       auto I = Cached.find(S);
1323       if (I != Cached.end())
1324         return I->second;
1325 
1326       // For now don't try to simplify mixed Loc/NonLoc expressions
1327       // because they often appear from LocAsInteger operations
1328       // and we don't know how to combine a LocAsInteger
1329       // with a concrete value.
1330       if (Loc::isLocType(S->getLHS()->getType()) !=
1331           Loc::isLocType(S->getRHS()->getType()))
1332         return skip(S);
1333 
1334       SVal LHS = Visit(S->getLHS());
1335       SVal RHS = Visit(S->getRHS());
1336       if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
1337         return skip(S);
1338 
1339       return cache(
1340           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1341     }
1342 
1343     SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
1344 
1345     SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
1346 
1347     SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
1348       // Simplification is much more costly than computing complexity.
1349       // For high complexity, it may be not worth it.
1350       return Visit(V.getSymbol());
1351     }
1352 
1353     SVal VisitSVal(SVal V) { return V; }
1354   };
1355 
1356   // A crude way of preventing this function from calling itself from evalBinOp.
1357   static bool isReentering = false;
1358   if (isReentering)
1359     return V;
1360 
1361   isReentering = true;
1362   SVal SimplifiedV = Simplifier(State).Visit(V);
1363   isReentering = false;
1364 
1365   return SimplifiedV;
1366 }
1367