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