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