10b57cec5SDimitry Andric // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
140b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
155ffd83dbSDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
160b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
170b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
18bdd1243dSDimitry Andric #include <optional>
190b57cec5SDimitry Andric 
200b57cec5SDimitry Andric using namespace clang;
210b57cec5SDimitry Andric using namespace ento;
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric namespace {
240b57cec5SDimitry Andric class SimpleSValBuilder : public SValBuilder {
250eae32dcSDimitry Andric 
2681ad6265SDimitry Andric   // Query the constraint manager whether the SVal has only one possible
2781ad6265SDimitry Andric   // (integer) value. If that is the case, the value is returned. Otherwise,
2881ad6265SDimitry Andric   // returns NULL.
2981ad6265SDimitry Andric   // This is an implementation detail. Checkers should use `getKnownValue()`
3081ad6265SDimitry Andric   // instead.
315f757f3fSDimitry Andric   static const llvm::APSInt *getConstValue(ProgramStateRef state, SVal V);
325f757f3fSDimitry Andric 
335f757f3fSDimitry Andric   // Helper function that returns the value stored in a nonloc::ConcreteInt or
345f757f3fSDimitry Andric   // loc::ConcreteInt.
355f757f3fSDimitry Andric   static const llvm::APSInt *getConcreteValue(SVal V);
3681ad6265SDimitry Andric 
370eae32dcSDimitry Andric   // With one `simplifySValOnce` call, a compound symbols might collapse to
380eae32dcSDimitry Andric   // simpler symbol tree that is still possible to further simplify. Thus, we
390eae32dcSDimitry Andric   // do the simplification on a new symbol tree until we reach the simplest
400eae32dcSDimitry Andric   // form, i.e. the fixpoint.
410eae32dcSDimitry Andric   // Consider the following symbol `(b * b) * b * b` which has this tree:
420eae32dcSDimitry Andric   //       *
430eae32dcSDimitry Andric   //      / \
440eae32dcSDimitry Andric   //     *   b
450eae32dcSDimitry Andric   //    /  \
460eae32dcSDimitry Andric   //   /    b
470eae32dcSDimitry Andric   // (b * b)
480eae32dcSDimitry Andric   // Now, if the `b * b == 1` new constraint is added then during the first
490eae32dcSDimitry Andric   // iteration we have the following transformations:
500eae32dcSDimitry Andric   //       *                  *
510eae32dcSDimitry Andric   //      / \                / \
520eae32dcSDimitry Andric   //     *   b     -->      b   b
530eae32dcSDimitry Andric   //    /  \
540eae32dcSDimitry Andric   //   /    b
550eae32dcSDimitry Andric   //  1
560eae32dcSDimitry Andric   // We need another iteration to reach the final result `1`.
570eae32dcSDimitry Andric   SVal simplifyUntilFixpoint(ProgramStateRef State, SVal Val);
580eae32dcSDimitry Andric 
590eae32dcSDimitry Andric   // Recursively descends into symbolic expressions and replaces symbols
6081ad6265SDimitry Andric   // with their known values (in the sense of the getConstValue() method).
610eae32dcSDimitry Andric   // We traverse the symbol tree and query the constraint values for the
620eae32dcSDimitry Andric   // sub-trees and if a value is a constant we do the constant folding.
630eae32dcSDimitry Andric   SVal simplifySValOnce(ProgramStateRef State, SVal V);
640eae32dcSDimitry Andric 
650b57cec5SDimitry Andric public:
SimpleSValBuilder(llvm::BumpPtrAllocator & alloc,ASTContext & context,ProgramStateManager & stateMgr)660b57cec5SDimitry Andric   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
670b57cec5SDimitry Andric                     ProgramStateManager &stateMgr)
680b57cec5SDimitry Andric       : SValBuilder(alloc, context, stateMgr) {}
~SimpleSValBuilder()690b57cec5SDimitry Andric   ~SimpleSValBuilder() override {}
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
720b57cec5SDimitry Andric                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
730b57cec5SDimitry Andric   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
740b57cec5SDimitry Andric                    Loc lhs, Loc rhs, QualType resultTy) override;
750b57cec5SDimitry Andric   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
760b57cec5SDimitry Andric                    Loc lhs, NonLoc rhs, QualType resultTy) override;
770b57cec5SDimitry Andric 
7881ad6265SDimitry Andric   /// Evaluates a given SVal by recursively evaluating and
7981ad6265SDimitry Andric   /// simplifying the children SVals. If the SVal has only one possible
800b57cec5SDimitry Andric   /// (integer) value, that value is returned. Otherwise, returns NULL.
810b57cec5SDimitry Andric   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
820b57cec5SDimitry Andric 
835f757f3fSDimitry Andric   /// Evaluates a given SVal by recursively evaluating and simplifying the
845f757f3fSDimitry Andric   /// children SVals, then returns its minimal possible (integer) value. If the
855f757f3fSDimitry Andric   /// constraint manager cannot provide a meaningful answer, this returns NULL.
865f757f3fSDimitry Andric   const llvm::APSInt *getMinValue(ProgramStateRef state, SVal V) override;
875f757f3fSDimitry Andric 
885f757f3fSDimitry Andric   /// Evaluates a given SVal by recursively evaluating and simplifying the
895f757f3fSDimitry Andric   /// children SVals, then returns its maximal possible (integer) value. If the
905f757f3fSDimitry Andric   /// constraint manager cannot provide a meaningful answer, this returns NULL.
915f757f3fSDimitry Andric   const llvm::APSInt *getMaxValue(ProgramStateRef state, SVal V) override;
925f757f3fSDimitry Andric 
930b57cec5SDimitry Andric   SVal simplifySVal(ProgramStateRef State, SVal V) override;
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
960b57cec5SDimitry Andric                      const llvm::APSInt &RHS, QualType resultTy);
970b57cec5SDimitry Andric };
980b57cec5SDimitry Andric } // end anonymous namespace
990b57cec5SDimitry Andric 
createSimpleSValBuilder(llvm::BumpPtrAllocator & alloc,ASTContext & context,ProgramStateManager & stateMgr)1000b57cec5SDimitry Andric SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
1010b57cec5SDimitry Andric                                            ASTContext &context,
1020b57cec5SDimitry Andric                                            ProgramStateManager &stateMgr) {
1030b57cec5SDimitry Andric   return new SimpleSValBuilder(alloc, context, stateMgr);
1040b57cec5SDimitry Andric }
1050b57cec5SDimitry Andric 
10681ad6265SDimitry Andric // Checks if the negation the value and flipping sign preserve
10781ad6265SDimitry Andric // the semantics on the operation in the resultType
isNegationValuePreserving(const llvm::APSInt & Value,APSIntType ResultType)10881ad6265SDimitry Andric static bool isNegationValuePreserving(const llvm::APSInt &Value,
10981ad6265SDimitry Andric                                       APSIntType ResultType) {
11081ad6265SDimitry Andric   const unsigned ValueBits = Value.getSignificantBits();
11181ad6265SDimitry Andric   if (ValueBits == ResultType.getBitWidth()) {
11281ad6265SDimitry Andric     // The value is the lowest negative value that is representable
11381ad6265SDimitry Andric     // in signed integer with bitWith of result type. The
11481ad6265SDimitry Andric     // negation is representable if resultType is unsigned.
11581ad6265SDimitry Andric     return ResultType.isUnsigned();
1160b57cec5SDimitry Andric   }
1170b57cec5SDimitry Andric 
11881ad6265SDimitry Andric   // If resultType bitWith is higher that number of bits required
11981ad6265SDimitry Andric   // to represent RHS, the sign flip produce same value.
12081ad6265SDimitry Andric   return ValueBits < ResultType.getBitWidth();
1210b57cec5SDimitry Andric }
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1240b57cec5SDimitry Andric // Transfer function for binary operators.
1250b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1260b57cec5SDimitry Andric 
MakeSymIntVal(const SymExpr * LHS,BinaryOperator::Opcode op,const llvm::APSInt & RHS,QualType resultTy)1270b57cec5SDimitry Andric SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
1280b57cec5SDimitry Andric                                     BinaryOperator::Opcode op,
1290b57cec5SDimitry Andric                                     const llvm::APSInt &RHS,
1300b57cec5SDimitry Andric                                     QualType resultTy) {
1310b57cec5SDimitry Andric   bool isIdempotent = false;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   // Check for a few special cases with known reductions first.
1340b57cec5SDimitry Andric   switch (op) {
1350b57cec5SDimitry Andric   default:
1360b57cec5SDimitry Andric     // We can't reduce this case; just treat it normally.
1370b57cec5SDimitry Andric     break;
1380b57cec5SDimitry Andric   case BO_Mul:
1390b57cec5SDimitry Andric     // a*0 and a*1
1400b57cec5SDimitry Andric     if (RHS == 0)
1410b57cec5SDimitry Andric       return makeIntVal(0, resultTy);
1420b57cec5SDimitry Andric     else if (RHS == 1)
1430b57cec5SDimitry Andric       isIdempotent = true;
1440b57cec5SDimitry Andric     break;
1450b57cec5SDimitry Andric   case BO_Div:
1460b57cec5SDimitry Andric     // a/0 and a/1
1470b57cec5SDimitry Andric     if (RHS == 0)
1480b57cec5SDimitry Andric       // This is also handled elsewhere.
1490b57cec5SDimitry Andric       return UndefinedVal();
1500b57cec5SDimitry Andric     else if (RHS == 1)
1510b57cec5SDimitry Andric       isIdempotent = true;
1520b57cec5SDimitry Andric     break;
1530b57cec5SDimitry Andric   case BO_Rem:
1540b57cec5SDimitry Andric     // a%0 and a%1
1550b57cec5SDimitry Andric     if (RHS == 0)
1560b57cec5SDimitry Andric       // This is also handled elsewhere.
1570b57cec5SDimitry Andric       return UndefinedVal();
1580b57cec5SDimitry Andric     else if (RHS == 1)
1590b57cec5SDimitry Andric       return makeIntVal(0, resultTy);
1600b57cec5SDimitry Andric     break;
1610b57cec5SDimitry Andric   case BO_Add:
1620b57cec5SDimitry Andric   case BO_Sub:
1630b57cec5SDimitry Andric   case BO_Shl:
1640b57cec5SDimitry Andric   case BO_Shr:
1650b57cec5SDimitry Andric   case BO_Xor:
1660b57cec5SDimitry Andric     // a+0, a-0, a<<0, a>>0, a^0
1670b57cec5SDimitry Andric     if (RHS == 0)
1680b57cec5SDimitry Andric       isIdempotent = true;
1690b57cec5SDimitry Andric     break;
1700b57cec5SDimitry Andric   case BO_And:
1710b57cec5SDimitry Andric     // a&0 and a&(~0)
1720b57cec5SDimitry Andric     if (RHS == 0)
1730b57cec5SDimitry Andric       return makeIntVal(0, resultTy);
174349cc55cSDimitry Andric     else if (RHS.isAllOnes())
1750b57cec5SDimitry Andric       isIdempotent = true;
1760b57cec5SDimitry Andric     break;
1770b57cec5SDimitry Andric   case BO_Or:
1780b57cec5SDimitry Andric     // a|0 and a|(~0)
1790b57cec5SDimitry Andric     if (RHS == 0)
1800b57cec5SDimitry Andric       isIdempotent = true;
181349cc55cSDimitry Andric     else if (RHS.isAllOnes()) {
1820b57cec5SDimitry Andric       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
1830b57cec5SDimitry Andric       return nonloc::ConcreteInt(Result);
1840b57cec5SDimitry Andric     }
1850b57cec5SDimitry Andric     break;
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   // Idempotent ops (like a*1) can still change the type of an expression.
189fe6060f1SDimitry Andric   // Wrap the LHS up in a NonLoc again and let evalCast do the
1900b57cec5SDimitry Andric   // dirty work.
1910b57cec5SDimitry Andric   if (isIdempotent)
192fe6060f1SDimitry Andric     return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{});
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   // If we reach this point, the expression cannot be simplified.
1950b57cec5SDimitry Andric   // Make a SymbolVal for the entire expression, after converting the RHS.
1960b57cec5SDimitry Andric   const llvm::APSInt *ConvertedRHS = &RHS;
1970b57cec5SDimitry Andric   if (BinaryOperator::isComparisonOp(op)) {
1980b57cec5SDimitry Andric     // We're looking for a type big enough to compare the symbolic value
1990b57cec5SDimitry Andric     // with the given constant.
2000b57cec5SDimitry Andric     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
2010b57cec5SDimitry Andric     ASTContext &Ctx = getContext();
2020b57cec5SDimitry Andric     QualType SymbolType = LHS->getType();
2030b57cec5SDimitry Andric     uint64_t ValWidth = RHS.getBitWidth();
2040b57cec5SDimitry Andric     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric     if (ValWidth < TypeWidth) {
2070b57cec5SDimitry Andric       // If the value is too small, extend it.
2080b57cec5SDimitry Andric       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
2090b57cec5SDimitry Andric     } else if (ValWidth == TypeWidth) {
2100b57cec5SDimitry Andric       // If the value is signed but the symbol is unsigned, do the comparison
2110b57cec5SDimitry Andric       // in unsigned space. [C99 6.3.1.8]
2120b57cec5SDimitry Andric       // (For the opposite case, the value is already unsigned.)
2130b57cec5SDimitry Andric       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
2140b57cec5SDimitry Andric         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
2150b57cec5SDimitry Andric     }
21681ad6265SDimitry Andric   } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) {
21781ad6265SDimitry Andric     // Change a+(-N) into a-N, and a-(-N) into a+N
21881ad6265SDimitry Andric     // Adjust addition/subtraction of negative value, to
21981ad6265SDimitry Andric     // subtraction/addition of the negated value.
22081ad6265SDimitry Andric     APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy);
22181ad6265SDimitry Andric     if (isNegationValuePreserving(RHS, resultIntTy)) {
22281ad6265SDimitry Andric       ConvertedRHS = &BasicVals.getValue(-resultIntTy.convert(RHS));
22381ad6265SDimitry Andric       op = (op == BO_Add) ? BO_Sub : BO_Add;
22481ad6265SDimitry Andric     } else {
22581ad6265SDimitry Andric       ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
22681ad6265SDimitry Andric     }
2270b57cec5SDimitry Andric   } else
2280b57cec5SDimitry Andric     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
2290b57cec5SDimitry Andric 
2300b57cec5SDimitry Andric   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric // See if Sym is known to be a relation Rel with Bound.
isInRelation(BinaryOperator::Opcode Rel,SymbolRef Sym,llvm::APSInt Bound,ProgramStateRef State)2340b57cec5SDimitry Andric static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
2350b57cec5SDimitry Andric                          llvm::APSInt Bound, ProgramStateRef State) {
2360b57cec5SDimitry Andric   SValBuilder &SVB = State->getStateManager().getSValBuilder();
2370b57cec5SDimitry Andric   SVal Result =
2380b57cec5SDimitry Andric       SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
2390b57cec5SDimitry Andric                       nonloc::ConcreteInt(Bound), SVB.getConditionType());
2400b57cec5SDimitry Andric   if (auto DV = Result.getAs<DefinedSVal>()) {
2410b57cec5SDimitry Andric     return !State->assume(*DV, false);
2420b57cec5SDimitry Andric   }
2430b57cec5SDimitry Andric   return false;
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric // See if Sym is known to be within [min/4, max/4], where min and max
2470b57cec5SDimitry Andric // are the bounds of the symbol's integral type. With such symbols,
2480b57cec5SDimitry Andric // some manipulations can be performed without the risk of overflow.
2490b57cec5SDimitry Andric // assume() doesn't cause infinite recursion because we should be dealing
2500b57cec5SDimitry Andric // with simpler symbols on every recursive call.
isWithinConstantOverflowBounds(SymbolRef Sym,ProgramStateRef State)2510b57cec5SDimitry Andric static bool isWithinConstantOverflowBounds(SymbolRef Sym,
2520b57cec5SDimitry Andric                                            ProgramStateRef State) {
2530b57cec5SDimitry Andric   SValBuilder &SVB = State->getStateManager().getSValBuilder();
2540b57cec5SDimitry Andric   BasicValueFactory &BV = SVB.getBasicValueFactory();
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric   QualType T = Sym->getType();
2570b57cec5SDimitry Andric   assert(T->isSignedIntegerOrEnumerationType() &&
2580b57cec5SDimitry Andric          "This only works with signed integers!");
2590b57cec5SDimitry Andric   APSIntType AT = BV.getAPSIntType(T);
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
2620b57cec5SDimitry Andric   return isInRelation(BO_LE, Sym, Max, State) &&
2630b57cec5SDimitry Andric          isInRelation(BO_GE, Sym, Min, State);
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric // Same for the concrete integers: see if I is within [min/4, max/4].
isWithinConstantOverflowBounds(llvm::APSInt I)2670b57cec5SDimitry Andric static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
2680b57cec5SDimitry Andric   APSIntType AT(I);
2690b57cec5SDimitry Andric   assert(!AT.isUnsigned() &&
2700b57cec5SDimitry Andric          "This only works with signed integers!");
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
2730b57cec5SDimitry Andric   return (I <= Max) && (I >= -Max);
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric static std::pair<SymbolRef, llvm::APSInt>
decomposeSymbol(SymbolRef Sym,BasicValueFactory & BV)2770b57cec5SDimitry Andric decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
2780b57cec5SDimitry Andric   if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
2790b57cec5SDimitry Andric     if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
2800b57cec5SDimitry Andric       return std::make_pair(SymInt->getLHS(),
2810b57cec5SDimitry Andric                             (SymInt->getOpcode() == BO_Add) ?
2820b57cec5SDimitry Andric                             (SymInt->getRHS()) :
2830b57cec5SDimitry Andric                             (-SymInt->getRHS()));
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   // Fail to decompose: "reduce" the problem to the "$x + 0" case.
2860b57cec5SDimitry Andric   return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
2870b57cec5SDimitry Andric }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
2900b57cec5SDimitry Andric // same signed integral type and no overflows occur (which should be checked
2910b57cec5SDimitry Andric // by the caller).
doRearrangeUnchecked(ProgramStateRef State,BinaryOperator::Opcode Op,SymbolRef LSym,llvm::APSInt LInt,SymbolRef RSym,llvm::APSInt RInt)2920b57cec5SDimitry Andric static NonLoc doRearrangeUnchecked(ProgramStateRef State,
2930b57cec5SDimitry Andric                                    BinaryOperator::Opcode Op,
2940b57cec5SDimitry Andric                                    SymbolRef LSym, llvm::APSInt LInt,
2950b57cec5SDimitry Andric                                    SymbolRef RSym, llvm::APSInt RInt) {
2960b57cec5SDimitry Andric   SValBuilder &SVB = State->getStateManager().getSValBuilder();
2970b57cec5SDimitry Andric   BasicValueFactory &BV = SVB.getBasicValueFactory();
2980b57cec5SDimitry Andric   SymbolManager &SymMgr = SVB.getSymbolManager();
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   QualType SymTy = LSym->getType();
3010b57cec5SDimitry Andric   assert(SymTy == RSym->getType() &&
3020b57cec5SDimitry Andric          "Symbols are not of the same type!");
3030b57cec5SDimitry Andric   assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
3040b57cec5SDimitry Andric          "Integers are not of the same type as symbols!");
3050b57cec5SDimitry Andric   assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
3060b57cec5SDimitry Andric          "Integers are not of the same type as symbols!");
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric   QualType ResultTy;
3090b57cec5SDimitry Andric   if (BinaryOperator::isComparisonOp(Op))
3100b57cec5SDimitry Andric     ResultTy = SVB.getConditionType();
3110b57cec5SDimitry Andric   else if (BinaryOperator::isAdditiveOp(Op))
3120b57cec5SDimitry Andric     ResultTy = SymTy;
3130b57cec5SDimitry Andric   else
3140b57cec5SDimitry Andric     llvm_unreachable("Operation not suitable for unchecked rearrangement!");
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric   if (LSym == RSym)
3170b57cec5SDimitry Andric     return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
3180b57cec5SDimitry Andric                            nonloc::ConcreteInt(RInt), ResultTy)
3190b57cec5SDimitry Andric         .castAs<NonLoc>();
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   SymbolRef ResultSym = nullptr;
3220b57cec5SDimitry Andric   BinaryOperator::Opcode ResultOp;
3230b57cec5SDimitry Andric   llvm::APSInt ResultInt;
3240b57cec5SDimitry Andric   if (BinaryOperator::isComparisonOp(Op)) {
3250b57cec5SDimitry Andric     // Prefer comparing to a non-negative number.
3260b57cec5SDimitry Andric     // FIXME: Maybe it'd be better to have consistency in
3270b57cec5SDimitry Andric     // "$x - $y" vs. "$y - $x" because those are solver's keys.
3280b57cec5SDimitry Andric     if (LInt > RInt) {
3290b57cec5SDimitry Andric       ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
3300b57cec5SDimitry Andric       ResultOp = BinaryOperator::reverseComparisonOp(Op);
3310b57cec5SDimitry Andric       ResultInt = LInt - RInt; // Opposite order!
3320b57cec5SDimitry Andric     } else {
3330b57cec5SDimitry Andric       ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
3340b57cec5SDimitry Andric       ResultOp = Op;
3350b57cec5SDimitry Andric       ResultInt = RInt - LInt; // Opposite order!
3360b57cec5SDimitry Andric     }
3370b57cec5SDimitry Andric   } else {
3380b57cec5SDimitry Andric     ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
3390b57cec5SDimitry Andric     ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
3400b57cec5SDimitry Andric     ResultOp = BO_Add;
3410b57cec5SDimitry Andric     // Bring back the cosmetic difference.
3420b57cec5SDimitry Andric     if (ResultInt < 0) {
3430b57cec5SDimitry Andric       ResultInt = -ResultInt;
3440b57cec5SDimitry Andric       ResultOp = BO_Sub;
3450b57cec5SDimitry Andric     } else if (ResultInt == 0) {
3460b57cec5SDimitry Andric       // Shortcut: Simplify "$x + 0" to "$x".
3470b57cec5SDimitry Andric       return nonloc::SymbolVal(ResultSym);
3480b57cec5SDimitry Andric     }
3490b57cec5SDimitry Andric   }
3500b57cec5SDimitry Andric   const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
3510b57cec5SDimitry Andric   return nonloc::SymbolVal(
3520b57cec5SDimitry Andric       SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
3530b57cec5SDimitry Andric }
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric // Rearrange if symbol type matches the result type and if the operator is a
3560b57cec5SDimitry Andric // comparison operator, both symbol and constant must be within constant
3570b57cec5SDimitry Andric // overflow bounds.
shouldRearrange(ProgramStateRef State,BinaryOperator::Opcode Op,SymbolRef Sym,llvm::APSInt Int,QualType Ty)3580b57cec5SDimitry Andric static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
3590b57cec5SDimitry Andric                             SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
3600b57cec5SDimitry Andric   return Sym->getType() == Ty &&
3610b57cec5SDimitry Andric     (!BinaryOperator::isComparisonOp(Op) ||
3620b57cec5SDimitry Andric      (isWithinConstantOverflowBounds(Sym, State) &&
3630b57cec5SDimitry Andric       isWithinConstantOverflowBounds(Int)));
3640b57cec5SDimitry Andric }
3650b57cec5SDimitry Andric 
tryRearrange(ProgramStateRef State,BinaryOperator::Opcode Op,NonLoc Lhs,NonLoc Rhs,QualType ResultTy)366bdd1243dSDimitry Andric static std::optional<NonLoc> tryRearrange(ProgramStateRef State,
3670b57cec5SDimitry Andric                                           BinaryOperator::Opcode Op, NonLoc Lhs,
3680b57cec5SDimitry Andric                                           NonLoc Rhs, QualType ResultTy) {
3690b57cec5SDimitry Andric   ProgramStateManager &StateMgr = State->getStateManager();
3700b57cec5SDimitry Andric   SValBuilder &SVB = StateMgr.getSValBuilder();
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric   // We expect everything to be of the same type - this type.
3730b57cec5SDimitry Andric   QualType SingleTy;
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   // FIXME: After putting complexity threshold to the symbols we can always
3760b57cec5SDimitry Andric   //        rearrange additive operations but rearrange comparisons only if
3770b57cec5SDimitry Andric   //        option is set.
378349cc55cSDimitry Andric   if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation)
379bdd1243dSDimitry Andric     return std::nullopt;
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric   SymbolRef LSym = Lhs.getAsSymbol();
3820b57cec5SDimitry Andric   if (!LSym)
383bdd1243dSDimitry Andric     return std::nullopt;
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   if (BinaryOperator::isComparisonOp(Op)) {
3860b57cec5SDimitry Andric     SingleTy = LSym->getType();
3870b57cec5SDimitry Andric     if (ResultTy != SVB.getConditionType())
388bdd1243dSDimitry Andric       return std::nullopt;
3890b57cec5SDimitry Andric     // Initialize SingleTy later with a symbol's type.
3900b57cec5SDimitry Andric   } else if (BinaryOperator::isAdditiveOp(Op)) {
3910b57cec5SDimitry Andric     SingleTy = ResultTy;
3920b57cec5SDimitry Andric     if (LSym->getType() != SingleTy)
393bdd1243dSDimitry Andric       return std::nullopt;
3940b57cec5SDimitry Andric   } else {
3950b57cec5SDimitry Andric     // Don't rearrange other operations.
396bdd1243dSDimitry Andric     return std::nullopt;
3970b57cec5SDimitry Andric   }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   assert(!SingleTy.isNull() && "We should have figured out the type by now!");
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric   // Rearrange signed symbolic expressions only
4020b57cec5SDimitry Andric   if (!SingleTy->isSignedIntegerOrEnumerationType())
403bdd1243dSDimitry Andric     return std::nullopt;
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   SymbolRef RSym = Rhs.getAsSymbol();
4060b57cec5SDimitry Andric   if (!RSym || RSym->getType() != SingleTy)
407bdd1243dSDimitry Andric     return std::nullopt;
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   BasicValueFactory &BV = State->getBasicVals();
4100b57cec5SDimitry Andric   llvm::APSInt LInt, RInt;
4110b57cec5SDimitry Andric   std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
4120b57cec5SDimitry Andric   std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
4130b57cec5SDimitry Andric   if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
4140b57cec5SDimitry Andric       !shouldRearrange(State, Op, RSym, RInt, SingleTy))
415bdd1243dSDimitry Andric     return std::nullopt;
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   // We know that no overflows can occur anymore.
4180b57cec5SDimitry Andric   return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
4190b57cec5SDimitry Andric }
4200b57cec5SDimitry Andric 
evalBinOpNN(ProgramStateRef state,BinaryOperator::Opcode op,NonLoc lhs,NonLoc rhs,QualType resultTy)4210b57cec5SDimitry Andric SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
4220b57cec5SDimitry Andric                                   BinaryOperator::Opcode op,
4230b57cec5SDimitry Andric                                   NonLoc lhs, NonLoc rhs,
4240b57cec5SDimitry Andric                                   QualType resultTy)  {
4250b57cec5SDimitry Andric   NonLoc InputLHS = lhs;
4260b57cec5SDimitry Andric   NonLoc InputRHS = rhs;
4270b57cec5SDimitry Andric 
4284824e7fdSDimitry Andric   // Constraints may have changed since the creation of a bound SVal. Check if
4294824e7fdSDimitry Andric   // the values can be simplified based on those new constraints.
4304824e7fdSDimitry Andric   SVal simplifiedLhs = simplifySVal(state, lhs);
4314824e7fdSDimitry Andric   SVal simplifiedRhs = simplifySVal(state, rhs);
4324824e7fdSDimitry Andric   if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>())
4334824e7fdSDimitry Andric     lhs = *simplifiedLhsAsNonLoc;
4344824e7fdSDimitry Andric   if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>())
4354824e7fdSDimitry Andric     rhs = *simplifiedRhsAsNonLoc;
4364824e7fdSDimitry Andric 
4370b57cec5SDimitry Andric   // Handle trivial case where left-side and right-side are the same.
4380b57cec5SDimitry Andric   if (lhs == rhs)
4390b57cec5SDimitry Andric     switch (op) {
4400b57cec5SDimitry Andric       default:
4410b57cec5SDimitry Andric         break;
4420b57cec5SDimitry Andric       case BO_EQ:
4430b57cec5SDimitry Andric       case BO_LE:
4440b57cec5SDimitry Andric       case BO_GE:
4450b57cec5SDimitry Andric         return makeTruthVal(true, resultTy);
4460b57cec5SDimitry Andric       case BO_LT:
4470b57cec5SDimitry Andric       case BO_GT:
4480b57cec5SDimitry Andric       case BO_NE:
4490b57cec5SDimitry Andric         return makeTruthVal(false, resultTy);
4500b57cec5SDimitry Andric       case BO_Xor:
4510b57cec5SDimitry Andric       case BO_Sub:
4520b57cec5SDimitry Andric         if (resultTy->isIntegralOrEnumerationType())
4530b57cec5SDimitry Andric           return makeIntVal(0, resultTy);
454fe6060f1SDimitry Andric         return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy,
455fe6060f1SDimitry Andric                         QualType{});
4560b57cec5SDimitry Andric       case BO_Or:
4570b57cec5SDimitry Andric       case BO_And:
458fe6060f1SDimitry Andric         return evalCast(lhs, resultTy, QualType{});
4590b57cec5SDimitry Andric     }
4600b57cec5SDimitry Andric 
46104eeddc0SDimitry Andric   while (true) {
4625f757f3fSDimitry Andric     switch (lhs.getKind()) {
4630b57cec5SDimitry Andric     default:
4640b57cec5SDimitry Andric       return makeSymExprValNN(op, lhs, rhs, resultTy);
4650b57cec5SDimitry Andric     case nonloc::PointerToMemberKind: {
4665f757f3fSDimitry Andric       assert(rhs.getKind() == nonloc::PointerToMemberKind &&
4670b57cec5SDimitry Andric              "Both SVals should have pointer-to-member-type");
4680b57cec5SDimitry Andric       auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
4690b57cec5SDimitry Andric            RPTM = rhs.castAs<nonloc::PointerToMember>();
4700b57cec5SDimitry Andric       auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
4710b57cec5SDimitry Andric       switch (op) {
4720b57cec5SDimitry Andric         case BO_EQ:
4730b57cec5SDimitry Andric           return makeTruthVal(LPTMD == RPTMD, resultTy);
4740b57cec5SDimitry Andric         case BO_NE:
4750b57cec5SDimitry Andric           return makeTruthVal(LPTMD != RPTMD, resultTy);
4760b57cec5SDimitry Andric         default:
4770b57cec5SDimitry Andric           return UnknownVal();
4780b57cec5SDimitry Andric       }
4790b57cec5SDimitry Andric     }
4800b57cec5SDimitry Andric     case nonloc::LocAsIntegerKind: {
4810b57cec5SDimitry Andric       Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
4825f757f3fSDimitry Andric       switch (rhs.getKind()) {
4830b57cec5SDimitry Andric       case nonloc::LocAsIntegerKind:
4840b57cec5SDimitry Andric         // FIXME: at the moment the implementation
4850b57cec5SDimitry Andric         // of modeling "pointers as integers" is not complete.
4860b57cec5SDimitry Andric         if (!BinaryOperator::isComparisonOp(op))
4870b57cec5SDimitry Andric           return UnknownVal();
4880b57cec5SDimitry Andric         return evalBinOpLL(state, op, lhsL,
4890b57cec5SDimitry Andric                            rhs.castAs<nonloc::LocAsInteger>().getLoc(),
4900b57cec5SDimitry Andric                            resultTy);
4910b57cec5SDimitry Andric       case nonloc::ConcreteIntKind: {
4920b57cec5SDimitry Andric         // FIXME: at the moment the implementation
4930b57cec5SDimitry Andric         // of modeling "pointers as integers" is not complete.
4940b57cec5SDimitry Andric         if (!BinaryOperator::isComparisonOp(op))
4950b57cec5SDimitry Andric           return UnknownVal();
4960b57cec5SDimitry Andric         // Transform the integer into a location and compare.
4970b57cec5SDimitry Andric         // FIXME: This only makes sense for comparisons. If we want to, say,
4980b57cec5SDimitry Andric         // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
4990b57cec5SDimitry Andric         // then pack it back into a LocAsInteger.
5000b57cec5SDimitry Andric         llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
5010b57cec5SDimitry Andric         // If the region has a symbolic base, pay attention to the type; it
5020b57cec5SDimitry Andric         // might be coming from a non-default address space. For non-symbolic
5030b57cec5SDimitry Andric         // regions it doesn't matter that much because such comparisons would
5040b57cec5SDimitry Andric         // most likely evaluate to concrete false anyway. FIXME: We might
5050b57cec5SDimitry Andric         // still need to handle the non-comparison case.
5060b57cec5SDimitry Andric         if (SymbolRef lSym = lhs.getAsLocSymbol(true))
5070b57cec5SDimitry Andric           BasicVals.getAPSIntType(lSym->getType()).apply(i);
5080b57cec5SDimitry Andric         else
5090b57cec5SDimitry Andric           BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
5100b57cec5SDimitry Andric         return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
5110b57cec5SDimitry Andric       }
5120b57cec5SDimitry Andric         default:
5130b57cec5SDimitry Andric           switch (op) {
5140b57cec5SDimitry Andric             case BO_EQ:
5150b57cec5SDimitry Andric               return makeTruthVal(false, resultTy);
5160b57cec5SDimitry Andric             case BO_NE:
5170b57cec5SDimitry Andric               return makeTruthVal(true, resultTy);
5180b57cec5SDimitry Andric             default:
5190b57cec5SDimitry Andric               // This case also handles pointer arithmetic.
5200b57cec5SDimitry Andric               return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
5210b57cec5SDimitry Andric           }
5220b57cec5SDimitry Andric         }
5230b57cec5SDimitry Andric     }
5240b57cec5SDimitry Andric     case nonloc::ConcreteIntKind: {
5250b57cec5SDimitry Andric       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric       // If we're dealing with two known constants, just perform the operation.
52881ad6265SDimitry Andric       if (const llvm::APSInt *KnownRHSValue = getConstValue(state, rhs)) {
5290b57cec5SDimitry Andric         llvm::APSInt RHSValue = *KnownRHSValue;
5300b57cec5SDimitry Andric         if (BinaryOperator::isComparisonOp(op)) {
5310b57cec5SDimitry Andric           // We're looking for a type big enough to compare the two values.
5320b57cec5SDimitry Andric           // FIXME: This is not correct. char + short will result in a promotion
5330b57cec5SDimitry Andric           // to int. Unfortunately we have lost types by this point.
5340b57cec5SDimitry Andric           APSIntType CompareType = std::max(APSIntType(LHSValue),
5350b57cec5SDimitry Andric                                             APSIntType(RHSValue));
5360b57cec5SDimitry Andric           CompareType.apply(LHSValue);
5370b57cec5SDimitry Andric           CompareType.apply(RHSValue);
5380b57cec5SDimitry Andric         } else if (!BinaryOperator::isShiftOp(op)) {
5390b57cec5SDimitry Andric           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
5400b57cec5SDimitry Andric           IntType.apply(LHSValue);
5410b57cec5SDimitry Andric           IntType.apply(RHSValue);
5420b57cec5SDimitry Andric         }
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric         const llvm::APSInt *Result =
5450b57cec5SDimitry Andric           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
5465f757f3fSDimitry Andric         if (!Result) {
5475f757f3fSDimitry Andric           if (op == BO_Shl || op == BO_Shr) {
5485f757f3fSDimitry Andric             // FIXME: At this point the constant folding claims that the result
5495f757f3fSDimitry Andric             // of a bitwise shift is undefined. However, constant folding
5505f757f3fSDimitry Andric             // relies on the inaccurate type information that is stored in the
5515f757f3fSDimitry Andric             // bit size of APSInt objects, and if we reached this point, then
5525f757f3fSDimitry Andric             // the checker core.BitwiseShift already determined that the shift
5535f757f3fSDimitry Andric             // is valid (in a PreStmt callback, by querying the real type from
5545f757f3fSDimitry Andric             // the AST node).
5555f757f3fSDimitry Andric             // To avoid embarrassing false positives, let's just say that we
5565f757f3fSDimitry Andric             // don't know anything about the result of the shift.
5575f757f3fSDimitry Andric             return UnknownVal();
5585f757f3fSDimitry Andric           }
5590b57cec5SDimitry Andric           return UndefinedVal();
5605f757f3fSDimitry Andric         }
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric         return nonloc::ConcreteInt(*Result);
5630b57cec5SDimitry Andric       }
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric       // Swap the left and right sides and flip the operator if doing so
5660b57cec5SDimitry Andric       // allows us to better reason about the expression (this is a form
5670b57cec5SDimitry Andric       // of expression canonicalization).
5680b57cec5SDimitry Andric       // While we're at it, catch some special cases for non-commutative ops.
5690b57cec5SDimitry Andric       switch (op) {
5700b57cec5SDimitry Andric       case BO_LT:
5710b57cec5SDimitry Andric       case BO_GT:
5720b57cec5SDimitry Andric       case BO_LE:
5730b57cec5SDimitry Andric       case BO_GE:
5740b57cec5SDimitry Andric         op = BinaryOperator::reverseComparisonOp(op);
575bdd1243dSDimitry Andric         [[fallthrough]];
5760b57cec5SDimitry Andric       case BO_EQ:
5770b57cec5SDimitry Andric       case BO_NE:
5780b57cec5SDimitry Andric       case BO_Add:
5790b57cec5SDimitry Andric       case BO_Mul:
5800b57cec5SDimitry Andric       case BO_And:
5810b57cec5SDimitry Andric       case BO_Xor:
5820b57cec5SDimitry Andric       case BO_Or:
5830b57cec5SDimitry Andric         std::swap(lhs, rhs);
5840b57cec5SDimitry Andric         continue;
5850b57cec5SDimitry Andric       case BO_Shr:
5860b57cec5SDimitry Andric         // (~0)>>a
587349cc55cSDimitry Andric         if (LHSValue.isAllOnes() && LHSValue.isSigned())
588fe6060f1SDimitry Andric           return evalCast(lhs, resultTy, QualType{});
589bdd1243dSDimitry Andric         [[fallthrough]];
5900b57cec5SDimitry Andric       case BO_Shl:
5910b57cec5SDimitry Andric         // 0<<a and 0>>a
5920b57cec5SDimitry Andric         if (LHSValue == 0)
593fe6060f1SDimitry Andric           return evalCast(lhs, resultTy, QualType{});
5940b57cec5SDimitry Andric         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
595fe6060f1SDimitry Andric       case BO_Div:
596fe6060f1SDimitry Andric         // 0 / x == 0
5975ffd83dbSDimitry Andric       case BO_Rem:
5985ffd83dbSDimitry Andric         // 0 % x == 0
5995ffd83dbSDimitry Andric         if (LHSValue == 0)
6005ffd83dbSDimitry Andric           return makeZeroVal(resultTy);
601bdd1243dSDimitry Andric         [[fallthrough]];
6020b57cec5SDimitry Andric       default:
6030b57cec5SDimitry Andric         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
6040b57cec5SDimitry Andric       }
6050b57cec5SDimitry Andric     }
6060b57cec5SDimitry Andric     case nonloc::SymbolValKind: {
6070b57cec5SDimitry Andric       // We only handle LHS as simple symbols or SymIntExprs.
6080b57cec5SDimitry Andric       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric       // LHS is a symbolic expression.
6110b57cec5SDimitry Andric       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric         // Is this a logical not? (!x is represented as x == 0.)
6140b57cec5SDimitry Andric         if (op == BO_EQ && rhs.isZeroConstant()) {
6150b57cec5SDimitry Andric           // We know how to negate certain expressions. Simplify them here.
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
6180b57cec5SDimitry Andric           switch (opc) {
6190b57cec5SDimitry Andric           default:
6200b57cec5SDimitry Andric             // We don't know how to negate this operation.
6210b57cec5SDimitry Andric             // Just handle it as if it were a normal comparison to 0.
6220b57cec5SDimitry Andric             break;
6230b57cec5SDimitry Andric           case BO_LAnd:
6240b57cec5SDimitry Andric           case BO_LOr:
6250b57cec5SDimitry Andric             llvm_unreachable("Logical operators handled by branching logic.");
6260b57cec5SDimitry Andric           case BO_Assign:
6270b57cec5SDimitry Andric           case BO_MulAssign:
6280b57cec5SDimitry Andric           case BO_DivAssign:
6290b57cec5SDimitry Andric           case BO_RemAssign:
6300b57cec5SDimitry Andric           case BO_AddAssign:
6310b57cec5SDimitry Andric           case BO_SubAssign:
6320b57cec5SDimitry Andric           case BO_ShlAssign:
6330b57cec5SDimitry Andric           case BO_ShrAssign:
6340b57cec5SDimitry Andric           case BO_AndAssign:
6350b57cec5SDimitry Andric           case BO_XorAssign:
6360b57cec5SDimitry Andric           case BO_OrAssign:
6370b57cec5SDimitry Andric           case BO_Comma:
6380b57cec5SDimitry Andric             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
6390b57cec5SDimitry Andric           case BO_PtrMemD:
6400b57cec5SDimitry Andric           case BO_PtrMemI:
6410b57cec5SDimitry Andric             llvm_unreachable("Pointer arithmetic not handled here.");
6420b57cec5SDimitry Andric           case BO_LT:
6430b57cec5SDimitry Andric           case BO_GT:
6440b57cec5SDimitry Andric           case BO_LE:
6450b57cec5SDimitry Andric           case BO_GE:
6460b57cec5SDimitry Andric           case BO_EQ:
6470b57cec5SDimitry Andric           case BO_NE:
6480b57cec5SDimitry Andric             assert(resultTy->isBooleanType() ||
6490b57cec5SDimitry Andric                    resultTy == getConditionType());
6500b57cec5SDimitry Andric             assert(symIntExpr->getType()->isBooleanType() ||
6510b57cec5SDimitry Andric                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
6520b57cec5SDimitry Andric                                                        getConditionType()));
6530b57cec5SDimitry Andric             // Negate the comparison and make a value.
6540b57cec5SDimitry Andric             opc = BinaryOperator::negateComparisonOp(opc);
6550b57cec5SDimitry Andric             return makeNonLoc(symIntExpr->getLHS(), opc,
6560b57cec5SDimitry Andric                 symIntExpr->getRHS(), resultTy);
6570b57cec5SDimitry Andric           }
6580b57cec5SDimitry Andric         }
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric         // For now, only handle expressions whose RHS is a constant.
66181ad6265SDimitry Andric         if (const llvm::APSInt *RHSValue = getConstValue(state, rhs)) {
6620b57cec5SDimitry Andric           // If both the LHS and the current expression are additive,
6630b57cec5SDimitry Andric           // fold their constants and try again.
6640b57cec5SDimitry Andric           if (BinaryOperator::isAdditiveOp(op)) {
6650b57cec5SDimitry Andric             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
6660b57cec5SDimitry Andric             if (BinaryOperator::isAdditiveOp(lop)) {
6670b57cec5SDimitry Andric               // Convert the two constants to a common type, then combine them.
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric               // resultTy may not be the best type to convert to, but it's
6700b57cec5SDimitry Andric               // probably the best choice in expressions with mixed type
6710b57cec5SDimitry Andric               // (such as x+1U+2LL). The rules for implicit conversions should
6720b57cec5SDimitry Andric               // choose a reasonable type to preserve the expression, and will
6730b57cec5SDimitry Andric               // at least match how the value is going to be used.
6740b57cec5SDimitry Andric               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
6750b57cec5SDimitry Andric               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
6760b57cec5SDimitry Andric               const llvm::APSInt &second = IntType.convert(*RHSValue);
6770b57cec5SDimitry Andric 
67881ad6265SDimitry Andric               // If the op and lop agrees, then we just need to
67981ad6265SDimitry Andric               // sum the constants. Otherwise, we change to operation
68081ad6265SDimitry Andric               // type if substraction would produce negative value
68181ad6265SDimitry Andric               // (and cause overflow for unsigned integers),
68281ad6265SDimitry Andric               // as consequence x+1U-10 produces x-9U, instead
68381ad6265SDimitry Andric               // of x+4294967287U, that would be produced without this
68481ad6265SDimitry Andric               // additional check.
6850b57cec5SDimitry Andric               const llvm::APSInt *newRHS;
68681ad6265SDimitry Andric               if (lop == op) {
6870b57cec5SDimitry Andric                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
68881ad6265SDimitry Andric               } else if (first >= second) {
6890b57cec5SDimitry Andric                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
69081ad6265SDimitry Andric                 op = lop;
69181ad6265SDimitry Andric               } else {
69281ad6265SDimitry Andric                 newRHS = BasicVals.evalAPSInt(BO_Sub, second, first);
69381ad6265SDimitry Andric               }
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric               assert(newRHS && "Invalid operation despite common type!");
6960b57cec5SDimitry Andric               rhs = nonloc::ConcreteInt(*newRHS);
6970b57cec5SDimitry Andric               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
6980b57cec5SDimitry Andric               continue;
6990b57cec5SDimitry Andric             }
7000b57cec5SDimitry Andric           }
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric           // Otherwise, make a SymIntExpr out of the expression.
7030b57cec5SDimitry Andric           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
7040b57cec5SDimitry Andric         }
7050b57cec5SDimitry Andric       }
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric       // Is the RHS a constant?
70881ad6265SDimitry Andric       if (const llvm::APSInt *RHSValue = getConstValue(state, rhs))
7090b57cec5SDimitry Andric         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
7100b57cec5SDimitry Andric 
711bdd1243dSDimitry Andric       if (std::optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
7120b57cec5SDimitry Andric         return *V;
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric       // Give up -- this is not a symbolic expression we can handle.
7150b57cec5SDimitry Andric       return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
7160b57cec5SDimitry Andric     }
7170b57cec5SDimitry Andric     }
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric }
7200b57cec5SDimitry Andric 
evalBinOpFieldRegionFieldRegion(const FieldRegion * LeftFR,const FieldRegion * RightFR,BinaryOperator::Opcode op,QualType resultTy,SimpleSValBuilder & SVB)7210b57cec5SDimitry Andric static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
7220b57cec5SDimitry Andric                                             const FieldRegion *RightFR,
7230b57cec5SDimitry Andric                                             BinaryOperator::Opcode op,
7240b57cec5SDimitry Andric                                             QualType resultTy,
7250b57cec5SDimitry Andric                                             SimpleSValBuilder &SVB) {
7260b57cec5SDimitry Andric   // Only comparisons are meaningful here!
7270b57cec5SDimitry Andric   if (!BinaryOperator::isComparisonOp(op))
7280b57cec5SDimitry Andric     return UnknownVal();
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   // Next, see if the two FRs have the same super-region.
7310b57cec5SDimitry Andric   // FIXME: This doesn't handle casts yet, and simply stripping the casts
7320b57cec5SDimitry Andric   // doesn't help.
7330b57cec5SDimitry Andric   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
7340b57cec5SDimitry Andric     return UnknownVal();
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   const FieldDecl *LeftFD = LeftFR->getDecl();
7370b57cec5SDimitry Andric   const FieldDecl *RightFD = RightFR->getDecl();
7380b57cec5SDimitry Andric   const RecordDecl *RD = LeftFD->getParent();
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric   // Make sure the two FRs are from the same kind of record. Just in case!
7410b57cec5SDimitry Andric   // FIXME: This is probably where inheritance would be a problem.
7420b57cec5SDimitry Andric   if (RD != RightFD->getParent())
7430b57cec5SDimitry Andric     return UnknownVal();
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   // We know for sure that the two fields are not the same, since that
7460b57cec5SDimitry Andric   // would have given us the same SVal.
7470b57cec5SDimitry Andric   if (op == BO_EQ)
7480b57cec5SDimitry Andric     return SVB.makeTruthVal(false, resultTy);
7490b57cec5SDimitry Andric   if (op == BO_NE)
7500b57cec5SDimitry Andric     return SVB.makeTruthVal(true, resultTy);
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric   // Iterate through the fields and see which one comes first.
7530b57cec5SDimitry Andric   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
7540b57cec5SDimitry Andric   // members and the units in which bit-fields reside have addresses that
7550b57cec5SDimitry Andric   // increase in the order in which they are declared."
7560b57cec5SDimitry Andric   bool leftFirst = (op == BO_LT || op == BO_LE);
7570b57cec5SDimitry Andric   for (const auto *I : RD->fields()) {
7580b57cec5SDimitry Andric     if (I == LeftFD)
7590b57cec5SDimitry Andric       return SVB.makeTruthVal(leftFirst, resultTy);
7600b57cec5SDimitry Andric     if (I == RightFD)
7610b57cec5SDimitry Andric       return SVB.makeTruthVal(!leftFirst, resultTy);
7620b57cec5SDimitry Andric   }
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   llvm_unreachable("Fields not found in parent record's definition");
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric 
76781ad6265SDimitry Andric // This is used in debug builds only for now because some downstream users
76881ad6265SDimitry Andric // may hit this assert in their subsequent merges.
76981ad6265SDimitry Andric // There are still places in the analyzer where equal bitwidth Locs
77081ad6265SDimitry Andric // are compared, and need to be found and corrected. Recent previous fixes have
77181ad6265SDimitry Andric // addressed the known problems of making NULLs with specific bitwidths
77281ad6265SDimitry Andric // for Loc comparisons along with deprecation of APIs for the same purpose.
77381ad6265SDimitry Andric //
assertEqualBitWidths(ProgramStateRef State,Loc RhsLoc,Loc LhsLoc)77481ad6265SDimitry Andric static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc,
77581ad6265SDimitry Andric                                  Loc LhsLoc) {
77681ad6265SDimitry Andric   // Implements a "best effort" check for RhsLoc and LhsLoc bit widths
77781ad6265SDimitry Andric   ASTContext &Ctx = State->getStateManager().getContext();
77881ad6265SDimitry Andric   uint64_t RhsBitwidth =
77981ad6265SDimitry Andric       RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx));
78081ad6265SDimitry Andric   uint64_t LhsBitwidth =
78181ad6265SDimitry Andric       LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx));
7825f757f3fSDimitry Andric   if (RhsBitwidth && LhsBitwidth && (LhsLoc.getKind() == RhsLoc.getKind())) {
78381ad6265SDimitry Andric     assert(RhsBitwidth == LhsBitwidth &&
78481ad6265SDimitry Andric            "RhsLoc and LhsLoc bitwidth must be same!");
78581ad6265SDimitry Andric   }
78681ad6265SDimitry Andric }
78781ad6265SDimitry Andric 
7880b57cec5SDimitry Andric // FIXME: all this logic will change if/when we have MemRegion::getLocation().
evalBinOpLL(ProgramStateRef state,BinaryOperator::Opcode op,Loc lhs,Loc rhs,QualType resultTy)7890b57cec5SDimitry Andric SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
7900b57cec5SDimitry Andric                                   BinaryOperator::Opcode op,
7910b57cec5SDimitry Andric                                   Loc lhs, Loc rhs,
7920b57cec5SDimitry Andric                                   QualType resultTy) {
79381ad6265SDimitry Andric 
79481ad6265SDimitry Andric   // Assert that bitwidth of lhs and rhs are the same.
79581ad6265SDimitry Andric   // This can happen if two different address spaces are used,
79681ad6265SDimitry Andric   // and the bitwidths of the address spaces are different.
79781ad6265SDimitry Andric   // See LIT case clang/test/Analysis/cstring-checker-addressspace.c
79881ad6265SDimitry Andric   // FIXME: See comment above in the function assertEqualBitWidths
79981ad6265SDimitry Andric   assertEqualBitWidths(state, rhs, lhs);
80081ad6265SDimitry Andric 
8010b57cec5SDimitry Andric   // Only comparisons and subtractions are valid operations on two pointers.
8020b57cec5SDimitry Andric   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
8030b57cec5SDimitry Andric   // However, if a pointer is casted to an integer, evalBinOpNN may end up
8040b57cec5SDimitry Andric   // calling this function with another operation (PR7527). We don't attempt to
8050b57cec5SDimitry Andric   // model this for now, but it could be useful, particularly when the
8060b57cec5SDimitry Andric   // "location" is actually an integer value that's been passed through a void*.
8070b57cec5SDimitry Andric   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
8080b57cec5SDimitry Andric     return UnknownVal();
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   // Special cases for when both sides are identical.
8110b57cec5SDimitry Andric   if (lhs == rhs) {
8120b57cec5SDimitry Andric     switch (op) {
8130b57cec5SDimitry Andric     default:
8140b57cec5SDimitry Andric       llvm_unreachable("Unimplemented operation for two identical values");
8150b57cec5SDimitry Andric     case BO_Sub:
8160b57cec5SDimitry Andric       return makeZeroVal(resultTy);
8170b57cec5SDimitry Andric     case BO_EQ:
8180b57cec5SDimitry Andric     case BO_LE:
8190b57cec5SDimitry Andric     case BO_GE:
8200b57cec5SDimitry Andric       return makeTruthVal(true, resultTy);
8210b57cec5SDimitry Andric     case BO_NE:
8220b57cec5SDimitry Andric     case BO_LT:
8230b57cec5SDimitry Andric     case BO_GT:
8240b57cec5SDimitry Andric       return makeTruthVal(false, resultTy);
8250b57cec5SDimitry Andric     }
8260b57cec5SDimitry Andric   }
8270b57cec5SDimitry Andric 
8285f757f3fSDimitry Andric   switch (lhs.getKind()) {
8290b57cec5SDimitry Andric   default:
8300b57cec5SDimitry Andric     llvm_unreachable("Ordering not implemented for this Loc.");
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   case loc::GotoLabelKind:
8330b57cec5SDimitry Andric     // The only thing we know about labels is that they're non-null.
8340b57cec5SDimitry Andric     if (rhs.isZeroConstant()) {
8350b57cec5SDimitry Andric       switch (op) {
8360b57cec5SDimitry Andric       default:
8370b57cec5SDimitry Andric         break;
8380b57cec5SDimitry Andric       case BO_Sub:
839fe6060f1SDimitry Andric         return evalCast(lhs, resultTy, QualType{});
8400b57cec5SDimitry Andric       case BO_EQ:
8410b57cec5SDimitry Andric       case BO_LE:
8420b57cec5SDimitry Andric       case BO_LT:
8430b57cec5SDimitry Andric         return makeTruthVal(false, resultTy);
8440b57cec5SDimitry Andric       case BO_NE:
8450b57cec5SDimitry Andric       case BO_GT:
8460b57cec5SDimitry Andric       case BO_GE:
8470b57cec5SDimitry Andric         return makeTruthVal(true, resultTy);
8480b57cec5SDimitry Andric       }
8490b57cec5SDimitry Andric     }
8500b57cec5SDimitry Andric     // There may be two labels for the same location, and a function region may
8510b57cec5SDimitry Andric     // have the same address as a label at the start of the function (depending
8520b57cec5SDimitry Andric     // on the ABI).
8530b57cec5SDimitry Andric     // FIXME: we can probably do a comparison against other MemRegions, though.
8540b57cec5SDimitry Andric     // FIXME: is there a way to tell if two labels refer to the same location?
8550b57cec5SDimitry Andric     return UnknownVal();
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric   case loc::ConcreteIntKind: {
85881ad6265SDimitry Andric     auto L = lhs.castAs<loc::ConcreteInt>();
85981ad6265SDimitry Andric 
8600b57cec5SDimitry Andric     // If one of the operands is a symbol and the other is a constant,
8610b57cec5SDimitry Andric     // build an expression for use by the constraint manager.
8620b57cec5SDimitry Andric     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
8630b57cec5SDimitry Andric       // We can only build expressions with symbols on the left,
8640b57cec5SDimitry Andric       // so we need a reversible operator.
8650b57cec5SDimitry Andric       if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
8660b57cec5SDimitry Andric         return UnknownVal();
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric       op = BinaryOperator::reverseComparisonOp(op);
86981ad6265SDimitry Andric       return makeNonLoc(rSym, op, L.getValue(), resultTy);
8700b57cec5SDimitry Andric     }
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric     // If both operands are constants, just perform the operation.
873bdd1243dSDimitry Andric     if (std::optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
87481ad6265SDimitry Andric       assert(BinaryOperator::isComparisonOp(op) || op == BO_Sub);
8750b57cec5SDimitry Andric 
87681ad6265SDimitry Andric       if (const auto *ResultInt =
87781ad6265SDimitry Andric               BasicVals.evalAPSInt(op, L.getValue(), rInt->getValue()))
87881ad6265SDimitry Andric         return evalCast(nonloc::ConcreteInt(*ResultInt), resultTy, QualType{});
8790b57cec5SDimitry Andric       return UnknownVal();
8800b57cec5SDimitry Andric     }
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric     // Special case comparisons against NULL.
8830b57cec5SDimitry Andric     // This must come after the test if the RHS is a symbol, which is used to
8840b57cec5SDimitry Andric     // build constraints. The address of any non-symbolic region is guaranteed
8850b57cec5SDimitry Andric     // to be non-NULL, as is any label.
88681ad6265SDimitry Andric     assert((isa<loc::MemRegionVal, loc::GotoLabel>(rhs)));
8870b57cec5SDimitry Andric     if (lhs.isZeroConstant()) {
8880b57cec5SDimitry Andric       switch (op) {
8890b57cec5SDimitry Andric       default:
8900b57cec5SDimitry Andric         break;
8910b57cec5SDimitry Andric       case BO_EQ:
8920b57cec5SDimitry Andric       case BO_GT:
8930b57cec5SDimitry Andric       case BO_GE:
8940b57cec5SDimitry Andric         return makeTruthVal(false, resultTy);
8950b57cec5SDimitry Andric       case BO_NE:
8960b57cec5SDimitry Andric       case BO_LT:
8970b57cec5SDimitry Andric       case BO_LE:
8980b57cec5SDimitry Andric         return makeTruthVal(true, resultTy);
8990b57cec5SDimitry Andric       }
9000b57cec5SDimitry Andric     }
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric     // Comparing an arbitrary integer to a region or label address is
9030b57cec5SDimitry Andric     // completely unknowable.
9040b57cec5SDimitry Andric     return UnknownVal();
9050b57cec5SDimitry Andric   }
9060b57cec5SDimitry Andric   case loc::MemRegionValKind: {
907bdd1243dSDimitry Andric     if (std::optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
9080b57cec5SDimitry Andric       // If one of the operands is a symbol and the other is a constant,
9090b57cec5SDimitry Andric       // build an expression for use by the constraint manager.
9100b57cec5SDimitry Andric       if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
9110b57cec5SDimitry Andric         if (BinaryOperator::isComparisonOp(op))
9120b57cec5SDimitry Andric           return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
9130b57cec5SDimitry Andric         return UnknownVal();
9140b57cec5SDimitry Andric       }
9150b57cec5SDimitry Andric       // Special case comparisons to NULL.
9160b57cec5SDimitry Andric       // This must come after the test if the LHS is a symbol, which is used to
9170b57cec5SDimitry Andric       // build constraints. The address of any non-symbolic region is guaranteed
9180b57cec5SDimitry Andric       // to be non-NULL.
9190b57cec5SDimitry Andric       if (rInt->isZeroConstant()) {
9200b57cec5SDimitry Andric         if (op == BO_Sub)
921fe6060f1SDimitry Andric           return evalCast(lhs, resultTy, QualType{});
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric         if (BinaryOperator::isComparisonOp(op)) {
9240b57cec5SDimitry Andric           QualType boolType = getContext().BoolTy;
925fe6060f1SDimitry Andric           NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>();
9260b57cec5SDimitry Andric           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
9270b57cec5SDimitry Andric           return evalBinOpNN(state, op, l, r, resultTy);
9280b57cec5SDimitry Andric         }
9290b57cec5SDimitry Andric       }
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric       // Comparing a region to an arbitrary integer is completely unknowable.
9320b57cec5SDimitry Andric       return UnknownVal();
9330b57cec5SDimitry Andric     }
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric     // Get both values as regions, if possible.
9360b57cec5SDimitry Andric     const MemRegion *LeftMR = lhs.getAsRegion();
9370b57cec5SDimitry Andric     assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric     const MemRegion *RightMR = rhs.getAsRegion();
9400b57cec5SDimitry Andric     if (!RightMR)
9410b57cec5SDimitry Andric       // The RHS is probably a label, which in theory could address a region.
9420b57cec5SDimitry Andric       // FIXME: we can probably make a more useful statement about non-code
9430b57cec5SDimitry Andric       // regions, though.
9440b57cec5SDimitry Andric       return UnknownVal();
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric     const MemRegion *LeftBase = LeftMR->getBaseRegion();
9470b57cec5SDimitry Andric     const MemRegion *RightBase = RightMR->getBaseRegion();
9480b57cec5SDimitry Andric     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
9490b57cec5SDimitry Andric     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
9500b57cec5SDimitry Andric     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric     // If the two regions are from different known memory spaces they cannot be
9530b57cec5SDimitry Andric     // equal. Also, assume that no symbolic region (whose memory space is
9540b57cec5SDimitry Andric     // unknown) is on the stack.
9550b57cec5SDimitry Andric     if (LeftMS != RightMS &&
9560b57cec5SDimitry Andric         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
9570b57cec5SDimitry Andric          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
9580b57cec5SDimitry Andric       switch (op) {
9590b57cec5SDimitry Andric       default:
9600b57cec5SDimitry Andric         return UnknownVal();
9610b57cec5SDimitry Andric       case BO_EQ:
9620b57cec5SDimitry Andric         return makeTruthVal(false, resultTy);
9630b57cec5SDimitry Andric       case BO_NE:
9640b57cec5SDimitry Andric         return makeTruthVal(true, resultTy);
9650b57cec5SDimitry Andric       }
9660b57cec5SDimitry Andric     }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric     // If both values wrap regions, see if they're from different base regions.
9690b57cec5SDimitry Andric     // Note, heap base symbolic regions are assumed to not alias with
9700b57cec5SDimitry Andric     // each other; for example, we assume that malloc returns different address
9710b57cec5SDimitry Andric     // on each invocation.
9720b57cec5SDimitry Andric     // FIXME: ObjC object pointers always reside on the heap, but currently
9730b57cec5SDimitry Andric     // we treat their memory space as unknown, because symbolic pointers
9740b57cec5SDimitry Andric     // to ObjC objects may alias. There should be a way to construct
9750b57cec5SDimitry Andric     // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
9760b57cec5SDimitry Andric     // guesses memory space for ObjC object pointers manually instead of
9770b57cec5SDimitry Andric     // relying on us.
9780b57cec5SDimitry Andric     if (LeftBase != RightBase &&
9790b57cec5SDimitry Andric         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
9800b57cec5SDimitry Andric          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
9810b57cec5SDimitry Andric       switch (op) {
9820b57cec5SDimitry Andric       default:
9830b57cec5SDimitry Andric         return UnknownVal();
9840b57cec5SDimitry Andric       case BO_EQ:
9850b57cec5SDimitry Andric         return makeTruthVal(false, resultTy);
9860b57cec5SDimitry Andric       case BO_NE:
9870b57cec5SDimitry Andric         return makeTruthVal(true, resultTy);
9880b57cec5SDimitry Andric       }
9890b57cec5SDimitry Andric     }
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric     // Handle special cases for when both regions are element regions.
9920b57cec5SDimitry Andric     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
9930b57cec5SDimitry Andric     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
9940b57cec5SDimitry Andric     if (RightER && LeftER) {
9950b57cec5SDimitry Andric       // Next, see if the two ERs have the same super-region and matching types.
9960b57cec5SDimitry Andric       // FIXME: This should do something useful even if the types don't match,
9970b57cec5SDimitry Andric       // though if both indexes are constant the RegionRawOffset path will
9980b57cec5SDimitry Andric       // give the correct answer.
9990b57cec5SDimitry Andric       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
10000b57cec5SDimitry Andric           LeftER->getElementType() == RightER->getElementType()) {
10010b57cec5SDimitry Andric         // Get the left index and cast it to the correct type.
10020b57cec5SDimitry Andric         // If the index is unknown or undefined, bail out here.
10030b57cec5SDimitry Andric         SVal LeftIndexVal = LeftER->getIndex();
1004bdd1243dSDimitry Andric         std::optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
10050b57cec5SDimitry Andric         if (!LeftIndex)
10060b57cec5SDimitry Andric           return UnknownVal();
1007fe6060f1SDimitry Andric         LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{});
10080b57cec5SDimitry Andric         LeftIndex = LeftIndexVal.getAs<NonLoc>();
10090b57cec5SDimitry Andric         if (!LeftIndex)
10100b57cec5SDimitry Andric           return UnknownVal();
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric         // Do the same for the right index.
10130b57cec5SDimitry Andric         SVal RightIndexVal = RightER->getIndex();
1014bdd1243dSDimitry Andric         std::optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
10150b57cec5SDimitry Andric         if (!RightIndex)
10160b57cec5SDimitry Andric           return UnknownVal();
1017fe6060f1SDimitry Andric         RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{});
10180b57cec5SDimitry Andric         RightIndex = RightIndexVal.getAs<NonLoc>();
10190b57cec5SDimitry Andric         if (!RightIndex)
10200b57cec5SDimitry Andric           return UnknownVal();
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric         // Actually perform the operation.
10230b57cec5SDimitry Andric         // evalBinOpNN expects the two indexes to already be the right type.
10240b57cec5SDimitry Andric         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
10250b57cec5SDimitry Andric       }
10260b57cec5SDimitry Andric     }
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric     // Special handling of the FieldRegions, even with symbolic offsets.
10290b57cec5SDimitry Andric     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
10300b57cec5SDimitry Andric     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
10310b57cec5SDimitry Andric     if (RightFR && LeftFR) {
10320b57cec5SDimitry Andric       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
10330b57cec5SDimitry Andric                                                *this);
10340b57cec5SDimitry Andric       if (!R.isUnknown())
10350b57cec5SDimitry Andric         return R;
10360b57cec5SDimitry Andric     }
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric     // Compare the regions using the raw offsets.
10390b57cec5SDimitry Andric     RegionOffset LeftOffset = LeftMR->getAsOffset();
10400b57cec5SDimitry Andric     RegionOffset RightOffset = RightMR->getAsOffset();
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric     if (LeftOffset.getRegion() != nullptr &&
10430b57cec5SDimitry Andric         LeftOffset.getRegion() == RightOffset.getRegion() &&
10440b57cec5SDimitry Andric         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
10450b57cec5SDimitry Andric       int64_t left = LeftOffset.getOffset();
10460b57cec5SDimitry Andric       int64_t right = RightOffset.getOffset();
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric       switch (op) {
10490b57cec5SDimitry Andric         default:
10500b57cec5SDimitry Andric           return UnknownVal();
10510b57cec5SDimitry Andric         case BO_LT:
10520b57cec5SDimitry Andric           return makeTruthVal(left < right, resultTy);
10530b57cec5SDimitry Andric         case BO_GT:
10540b57cec5SDimitry Andric           return makeTruthVal(left > right, resultTy);
10550b57cec5SDimitry Andric         case BO_LE:
10560b57cec5SDimitry Andric           return makeTruthVal(left <= right, resultTy);
10570b57cec5SDimitry Andric         case BO_GE:
10580b57cec5SDimitry Andric           return makeTruthVal(left >= right, resultTy);
10590b57cec5SDimitry Andric         case BO_EQ:
10600b57cec5SDimitry Andric           return makeTruthVal(left == right, resultTy);
10610b57cec5SDimitry Andric         case BO_NE:
10620b57cec5SDimitry Andric           return makeTruthVal(left != right, resultTy);
10630b57cec5SDimitry Andric       }
10640b57cec5SDimitry Andric     }
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric     // At this point we're not going to get a good answer, but we can try
10670b57cec5SDimitry Andric     // conjuring an expression instead.
10680b57cec5SDimitry Andric     SymbolRef LHSSym = lhs.getAsLocSymbol();
10690b57cec5SDimitry Andric     SymbolRef RHSSym = rhs.getAsLocSymbol();
10700b57cec5SDimitry Andric     if (LHSSym && RHSSym)
10710b57cec5SDimitry Andric       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric     // If we get here, we have no way of comparing the regions.
10740b57cec5SDimitry Andric     return UnknownVal();
10750b57cec5SDimitry Andric   }
10760b57cec5SDimitry Andric   }
10770b57cec5SDimitry Andric }
10780b57cec5SDimitry Andric 
evalBinOpLN(ProgramStateRef state,BinaryOperator::Opcode op,Loc lhs,NonLoc rhs,QualType resultTy)10790b57cec5SDimitry Andric SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
1080e8d8bef9SDimitry Andric                                     BinaryOperator::Opcode op, Loc lhs,
1081e8d8bef9SDimitry Andric                                     NonLoc rhs, QualType resultTy) {
10820b57cec5SDimitry Andric   if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
10830b57cec5SDimitry Andric     if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
10840b57cec5SDimitry Andric       if (PTMSV->isNullMemberPointer())
10850b57cec5SDimitry Andric         return UndefinedVal();
1086e8d8bef9SDimitry Andric 
1087e8d8bef9SDimitry Andric       auto getFieldLValue = [&](const auto *FD) -> SVal {
10880b57cec5SDimitry Andric         SVal Result = lhs;
10890b57cec5SDimitry Andric 
10900b57cec5SDimitry Andric         for (const auto &I : *PTMSV)
10910b57cec5SDimitry Andric           Result = StateMgr.getStoreManager().evalDerivedToBase(
10920b57cec5SDimitry Andric               Result, I->getType(), I->isVirtual());
1093e8d8bef9SDimitry Andric 
10940b57cec5SDimitry Andric         return state->getLValue(FD, Result);
1095e8d8bef9SDimitry Andric       };
1096e8d8bef9SDimitry Andric 
1097e8d8bef9SDimitry Andric       if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) {
1098e8d8bef9SDimitry Andric         return getFieldLValue(FD);
1099e8d8bef9SDimitry Andric       }
1100e8d8bef9SDimitry Andric       if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) {
1101e8d8bef9SDimitry Andric         return getFieldLValue(FD);
11020b57cec5SDimitry Andric       }
11030b57cec5SDimitry Andric     }
11040b57cec5SDimitry Andric 
11050b57cec5SDimitry Andric     return rhs;
11060b57cec5SDimitry Andric   }
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric   assert(!BinaryOperator::isComparisonOp(op) &&
11090b57cec5SDimitry Andric          "arguments to comparison ops must be of the same type");
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric   // Special case: rhs is a zero constant.
11120b57cec5SDimitry Andric   if (rhs.isZeroConstant())
11130b57cec5SDimitry Andric     return lhs;
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   // Perserve the null pointer so that it can be found by the DerefChecker.
11160b57cec5SDimitry Andric   if (lhs.isZeroConstant())
11170b57cec5SDimitry Andric     return lhs;
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric   // We are dealing with pointer arithmetic.
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric   // Handle pointer arithmetic on constant values.
1122bdd1243dSDimitry Andric   if (std::optional<nonloc::ConcreteInt> rhsInt =
1123bdd1243dSDimitry Andric           rhs.getAs<nonloc::ConcreteInt>()) {
1124bdd1243dSDimitry Andric     if (std::optional<loc::ConcreteInt> lhsInt =
1125bdd1243dSDimitry Andric             lhs.getAs<loc::ConcreteInt>()) {
11260b57cec5SDimitry Andric       const llvm::APSInt &leftI = lhsInt->getValue();
11270b57cec5SDimitry Andric       assert(leftI.isUnsigned());
11280b57cec5SDimitry Andric       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric       // Convert the bitwidth of rightI.  This should deal with overflow
11310b57cec5SDimitry Andric       // since we are dealing with concrete values.
11320b57cec5SDimitry Andric       rightI = rightI.extOrTrunc(leftI.getBitWidth());
11330b57cec5SDimitry Andric 
11340b57cec5SDimitry Andric       // Offset the increment by the pointer size.
11350b57cec5SDimitry Andric       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
11360b57cec5SDimitry Andric       QualType pointeeType = resultTy->getPointeeType();
11370b57cec5SDimitry Andric       Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
11380b57cec5SDimitry Andric       rightI *= Multiplicand;
11390b57cec5SDimitry Andric 
11400b57cec5SDimitry Andric       // Compute the adjusted pointer.
11410b57cec5SDimitry Andric       switch (op) {
11420b57cec5SDimitry Andric         case BO_Add:
11430b57cec5SDimitry Andric           rightI = leftI + rightI;
11440b57cec5SDimitry Andric           break;
11450b57cec5SDimitry Andric         case BO_Sub:
11460b57cec5SDimitry Andric           rightI = leftI - rightI;
11470b57cec5SDimitry Andric           break;
11480b57cec5SDimitry Andric         default:
11490b57cec5SDimitry Andric           llvm_unreachable("Invalid pointer arithmetic operation");
11500b57cec5SDimitry Andric       }
11510b57cec5SDimitry Andric       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
11520b57cec5SDimitry Andric     }
11530b57cec5SDimitry Andric   }
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric   // Handle cases where 'lhs' is a region.
11560b57cec5SDimitry Andric   if (const MemRegion *region = lhs.getAsRegion()) {
11570b57cec5SDimitry Andric     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
11580b57cec5SDimitry Andric     SVal index = UnknownVal();
11590b57cec5SDimitry Andric     const SubRegion *superR = nullptr;
11600b57cec5SDimitry Andric     // We need to know the type of the pointer in order to add an integer to it.
11610b57cec5SDimitry Andric     // Depending on the type, different amount of bytes is added.
11620b57cec5SDimitry Andric     QualType elementType;
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
11650b57cec5SDimitry Andric       assert(op == BO_Add || op == BO_Sub);
11660b57cec5SDimitry Andric       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
11670b57cec5SDimitry Andric                           getArrayIndexType());
11680b57cec5SDimitry Andric       superR = cast<SubRegion>(elemReg->getSuperRegion());
11690b57cec5SDimitry Andric       elementType = elemReg->getElementType();
11700b57cec5SDimitry Andric     }
11710b57cec5SDimitry Andric     else if (isa<SubRegion>(region)) {
11720b57cec5SDimitry Andric       assert(op == BO_Add || op == BO_Sub);
11730b57cec5SDimitry Andric       index = (op == BO_Add) ? rhs : evalMinus(rhs);
11740b57cec5SDimitry Andric       superR = cast<SubRegion>(region);
11750b57cec5SDimitry Andric       // TODO: Is this actually reliable? Maybe improving our MemRegion
11760b57cec5SDimitry Andric       // hierarchy to provide typed regions for all non-void pointers would be
11770b57cec5SDimitry Andric       // better. For instance, we cannot extend this towards LocAsInteger
11780b57cec5SDimitry Andric       // operations, where result type of the expression is integer.
11790b57cec5SDimitry Andric       if (resultTy->isAnyPointerType())
11800b57cec5SDimitry Andric         elementType = resultTy->getPointeeType();
11810b57cec5SDimitry Andric     }
11820b57cec5SDimitry Andric 
11830b57cec5SDimitry Andric     // Represent arithmetic on void pointers as arithmetic on char pointers.
11840b57cec5SDimitry Andric     // It is fine when a TypedValueRegion of char value type represents
11850b57cec5SDimitry Andric     // a void pointer. Note that arithmetic on void pointers is a GCC extension.
11860b57cec5SDimitry Andric     if (elementType->isVoidType())
11870b57cec5SDimitry Andric       elementType = getContext().CharTy;
11880b57cec5SDimitry Andric 
1189bdd1243dSDimitry Andric     if (std::optional<NonLoc> indexV = index.getAs<NonLoc>()) {
11900b57cec5SDimitry Andric       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
11910b57cec5SDimitry Andric                                                        superR, getContext()));
11920b57cec5SDimitry Andric     }
11930b57cec5SDimitry Andric   }
11940b57cec5SDimitry Andric   return UnknownVal();
11950b57cec5SDimitry Andric }
11960b57cec5SDimitry Andric 
getConstValue(ProgramStateRef state,SVal V)119781ad6265SDimitry Andric const llvm::APSInt *SimpleSValBuilder::getConstValue(ProgramStateRef state,
11980b57cec5SDimitry Andric                                                      SVal V) {
11995f757f3fSDimitry Andric   if (const llvm::APSInt *Res = getConcreteValue(V))
12005f757f3fSDimitry Andric     return Res;
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric   if (SymbolRef Sym = V.getAsSymbol())
12030b57cec5SDimitry Andric     return state->getConstraintManager().getSymVal(state, Sym);
12040b57cec5SDimitry Andric 
12050b57cec5SDimitry Andric   return nullptr;
12060b57cec5SDimitry Andric }
12070b57cec5SDimitry Andric 
getConcreteValue(SVal V)12085f757f3fSDimitry Andric const llvm::APSInt *SimpleSValBuilder::getConcreteValue(SVal V) {
12095f757f3fSDimitry Andric   if (std::optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
12105f757f3fSDimitry Andric     return &X->getValue();
12115f757f3fSDimitry Andric 
12125f757f3fSDimitry Andric   if (std::optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
12135f757f3fSDimitry Andric     return &X->getValue();
12145f757f3fSDimitry Andric 
12155f757f3fSDimitry Andric   return nullptr;
12165f757f3fSDimitry Andric }
12175f757f3fSDimitry Andric 
getKnownValue(ProgramStateRef state,SVal V)121881ad6265SDimitry Andric const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
121981ad6265SDimitry Andric                                                      SVal V) {
122081ad6265SDimitry Andric   return getConstValue(state, simplifySVal(state, V));
122181ad6265SDimitry Andric }
122281ad6265SDimitry Andric 
getMinValue(ProgramStateRef state,SVal V)12235f757f3fSDimitry Andric const llvm::APSInt *SimpleSValBuilder::getMinValue(ProgramStateRef state,
12245f757f3fSDimitry Andric                                                    SVal V) {
12255f757f3fSDimitry Andric   V = simplifySVal(state, V);
12265f757f3fSDimitry Andric 
12275f757f3fSDimitry Andric   if (const llvm::APSInt *Res = getConcreteValue(V))
12285f757f3fSDimitry Andric     return Res;
12295f757f3fSDimitry Andric 
12305f757f3fSDimitry Andric   if (SymbolRef Sym = V.getAsSymbol())
12315f757f3fSDimitry Andric     return state->getConstraintManager().getSymMinVal(state, Sym);
12325f757f3fSDimitry Andric 
12335f757f3fSDimitry Andric   return nullptr;
12345f757f3fSDimitry Andric }
12355f757f3fSDimitry Andric 
getMaxValue(ProgramStateRef state,SVal V)12365f757f3fSDimitry Andric const llvm::APSInt *SimpleSValBuilder::getMaxValue(ProgramStateRef state,
12375f757f3fSDimitry Andric                                                    SVal V) {
12385f757f3fSDimitry Andric   V = simplifySVal(state, V);
12395f757f3fSDimitry Andric 
12405f757f3fSDimitry Andric   if (const llvm::APSInt *Res = getConcreteValue(V))
12415f757f3fSDimitry Andric     return Res;
12425f757f3fSDimitry Andric 
12435f757f3fSDimitry Andric   if (SymbolRef Sym = V.getAsSymbol())
12445f757f3fSDimitry Andric     return state->getConstraintManager().getSymMaxVal(state, Sym);
12455f757f3fSDimitry Andric 
12465f757f3fSDimitry Andric   return nullptr;
12475f757f3fSDimitry Andric }
12485f757f3fSDimitry Andric 
simplifyUntilFixpoint(ProgramStateRef State,SVal Val)12490eae32dcSDimitry Andric SVal SimpleSValBuilder::simplifyUntilFixpoint(ProgramStateRef State, SVal Val) {
12500eae32dcSDimitry Andric   SVal SimplifiedVal = simplifySValOnce(State, Val);
12510eae32dcSDimitry Andric   while (SimplifiedVal != Val) {
12520eae32dcSDimitry Andric     Val = SimplifiedVal;
12530eae32dcSDimitry Andric     SimplifiedVal = simplifySValOnce(State, Val);
12540eae32dcSDimitry Andric   }
12550eae32dcSDimitry Andric   return SimplifiedVal;
12560eae32dcSDimitry Andric }
12570eae32dcSDimitry Andric 
simplifySVal(ProgramStateRef State,SVal V)12580b57cec5SDimitry Andric SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
12590eae32dcSDimitry Andric   return simplifyUntilFixpoint(State, V);
12600eae32dcSDimitry Andric }
12610eae32dcSDimitry Andric 
simplifySValOnce(ProgramStateRef State,SVal V)12620eae32dcSDimitry Andric SVal SimpleSValBuilder::simplifySValOnce(ProgramStateRef State, SVal V) {
12630b57cec5SDimitry Andric   // For now, this function tries to constant-fold symbols inside a
12640b57cec5SDimitry Andric   // nonloc::SymbolVal, and does nothing else. More simplifications should
12650b57cec5SDimitry Andric   // be possible, such as constant-folding an index in an ElementRegion.
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric   class Simplifier : public FullSValVisitor<Simplifier, SVal> {
12680b57cec5SDimitry Andric     ProgramStateRef State;
12690b57cec5SDimitry Andric     SValBuilder &SVB;
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric     // Cache results for the lifetime of the Simplifier. Results change every
12720b57cec5SDimitry Andric     // time new constraints are added to the program state, which is the whole
12730b57cec5SDimitry Andric     // point of simplifying, and for that very reason it's pointless to maintain
12740b57cec5SDimitry Andric     // the same cache for the duration of the whole analysis.
12750b57cec5SDimitry Andric     llvm::DenseMap<SymbolRef, SVal> Cached;
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric     static bool isUnchanged(SymbolRef Sym, SVal Val) {
12780b57cec5SDimitry Andric       return Sym == Val.getAsSymbol();
12790b57cec5SDimitry Andric     }
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric     SVal cache(SymbolRef Sym, SVal V) {
12820b57cec5SDimitry Andric       Cached[Sym] = V;
12830b57cec5SDimitry Andric       return V;
12840b57cec5SDimitry Andric     }
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric     SVal skip(SymbolRef Sym) {
12870b57cec5SDimitry Andric       return cache(Sym, SVB.makeSymbolVal(Sym));
12880b57cec5SDimitry Andric     }
12890b57cec5SDimitry Andric 
12904824e7fdSDimitry Andric     // Return the known const value for the Sym if available, or return Undef
12914824e7fdSDimitry Andric     // otherwise.
12924824e7fdSDimitry Andric     SVal getConst(SymbolRef Sym) {
12934824e7fdSDimitry Andric       const llvm::APSInt *Const =
12944824e7fdSDimitry Andric           State->getConstraintManager().getSymVal(State, Sym);
12954824e7fdSDimitry Andric       if (Const)
12964824e7fdSDimitry Andric         return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const)
12974824e7fdSDimitry Andric                                               : (SVal)SVB.makeIntVal(*Const);
12984824e7fdSDimitry Andric       return UndefinedVal();
12994824e7fdSDimitry Andric     }
13004824e7fdSDimitry Andric 
13014824e7fdSDimitry Andric     SVal getConstOrVisit(SymbolRef Sym) {
13024824e7fdSDimitry Andric       const SVal Ret = getConst(Sym);
13034824e7fdSDimitry Andric       if (Ret.isUndef())
13044824e7fdSDimitry Andric         return Visit(Sym);
13054824e7fdSDimitry Andric       return Ret;
13064824e7fdSDimitry Andric     }
13074824e7fdSDimitry Andric 
13080b57cec5SDimitry Andric   public:
13090b57cec5SDimitry Andric     Simplifier(ProgramStateRef State)
13100b57cec5SDimitry Andric         : State(State), SVB(State->getStateManager().getSValBuilder()) {}
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric     SVal VisitSymbolData(const SymbolData *S) {
13130b57cec5SDimitry Andric       // No cache here.
13140b57cec5SDimitry Andric       if (const llvm::APSInt *I =
131581ad6265SDimitry Andric               State->getConstraintManager().getSymVal(State, S))
13160b57cec5SDimitry Andric         return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
13170b57cec5SDimitry Andric                                             : (SVal)SVB.makeIntVal(*I);
13180b57cec5SDimitry Andric       return SVB.makeSymbolVal(S);
13190b57cec5SDimitry Andric     }
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric     SVal VisitSymIntExpr(const SymIntExpr *S) {
13220b57cec5SDimitry Andric       auto I = Cached.find(S);
13230b57cec5SDimitry Andric       if (I != Cached.end())
13240b57cec5SDimitry Andric         return I->second;
13250b57cec5SDimitry Andric 
13264824e7fdSDimitry Andric       SVal LHS = getConstOrVisit(S->getLHS());
13270b57cec5SDimitry Andric       if (isUnchanged(S->getLHS(), LHS))
13280b57cec5SDimitry Andric         return skip(S);
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric       SVal RHS;
13310b57cec5SDimitry Andric       // By looking at the APSInt in the right-hand side of S, we cannot
13320b57cec5SDimitry Andric       // figure out if it should be treated as a Loc or as a NonLoc.
13330b57cec5SDimitry Andric       // So make our guess by recalling that we cannot multiply pointers
13340b57cec5SDimitry Andric       // or compare a pointer to an integer.
13350b57cec5SDimitry Andric       if (Loc::isLocType(S->getLHS()->getType()) &&
13360b57cec5SDimitry Andric           BinaryOperator::isComparisonOp(S->getOpcode())) {
13370b57cec5SDimitry Andric         // The usual conversion of $sym to &SymRegion{$sym}, as they have
13380b57cec5SDimitry Andric         // the same meaning for Loc-type symbols, but the latter form
13390b57cec5SDimitry Andric         // is preferred in SVal computations for being Loc itself.
13400b57cec5SDimitry Andric         if (SymbolRef Sym = LHS.getAsSymbol()) {
13410b57cec5SDimitry Andric           assert(Loc::isLocType(Sym->getType()));
13420b57cec5SDimitry Andric           LHS = SVB.makeLoc(Sym);
13430b57cec5SDimitry Andric         }
13440b57cec5SDimitry Andric         RHS = SVB.makeIntLocVal(S->getRHS());
13450b57cec5SDimitry Andric       } else {
13460b57cec5SDimitry Andric         RHS = SVB.makeIntVal(S->getRHS());
13470b57cec5SDimitry Andric       }
13480b57cec5SDimitry Andric 
13490b57cec5SDimitry Andric       return cache(
13500b57cec5SDimitry Andric           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
13510b57cec5SDimitry Andric     }
13520b57cec5SDimitry Andric 
13534824e7fdSDimitry Andric     SVal VisitIntSymExpr(const IntSymExpr *S) {
13544824e7fdSDimitry Andric       auto I = Cached.find(S);
13554824e7fdSDimitry Andric       if (I != Cached.end())
13564824e7fdSDimitry Andric         return I->second;
13574824e7fdSDimitry Andric 
13584824e7fdSDimitry Andric       SVal RHS = getConstOrVisit(S->getRHS());
13594824e7fdSDimitry Andric       if (isUnchanged(S->getRHS(), RHS))
13604824e7fdSDimitry Andric         return skip(S);
13614824e7fdSDimitry Andric 
13624824e7fdSDimitry Andric       SVal LHS = SVB.makeIntVal(S->getLHS());
13634824e7fdSDimitry Andric       return cache(
13644824e7fdSDimitry Andric           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
13654824e7fdSDimitry Andric     }
13664824e7fdSDimitry Andric 
13670b57cec5SDimitry Andric     SVal VisitSymSymExpr(const SymSymExpr *S) {
13680b57cec5SDimitry Andric       auto I = Cached.find(S);
13690b57cec5SDimitry Andric       if (I != Cached.end())
13700b57cec5SDimitry Andric         return I->second;
13710b57cec5SDimitry Andric 
13720b57cec5SDimitry Andric       // For now don't try to simplify mixed Loc/NonLoc expressions
13730b57cec5SDimitry Andric       // because they often appear from LocAsInteger operations
13740b57cec5SDimitry Andric       // and we don't know how to combine a LocAsInteger
13750b57cec5SDimitry Andric       // with a concrete value.
13760b57cec5SDimitry Andric       if (Loc::isLocType(S->getLHS()->getType()) !=
13770b57cec5SDimitry Andric           Loc::isLocType(S->getRHS()->getType()))
13780b57cec5SDimitry Andric         return skip(S);
13790b57cec5SDimitry Andric 
13804824e7fdSDimitry Andric       SVal LHS = getConstOrVisit(S->getLHS());
13814824e7fdSDimitry Andric       SVal RHS = getConstOrVisit(S->getRHS());
13824824e7fdSDimitry Andric 
13830b57cec5SDimitry Andric       if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
13840b57cec5SDimitry Andric         return skip(S);
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric       return cache(
13870b57cec5SDimitry Andric           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
13880b57cec5SDimitry Andric     }
13890b57cec5SDimitry Andric 
139081ad6265SDimitry Andric     SVal VisitSymbolCast(const SymbolCast *S) {
139181ad6265SDimitry Andric       auto I = Cached.find(S);
139281ad6265SDimitry Andric       if (I != Cached.end())
139381ad6265SDimitry Andric         return I->second;
139481ad6265SDimitry Andric       const SymExpr *OpSym = S->getOperand();
139581ad6265SDimitry Andric       SVal OpVal = getConstOrVisit(OpSym);
139681ad6265SDimitry Andric       if (isUnchanged(OpSym, OpVal))
139781ad6265SDimitry Andric         return skip(S);
139881ad6265SDimitry Andric 
139981ad6265SDimitry Andric       return cache(S, SVB.evalCast(OpVal, S->getType(), OpSym->getType()));
140081ad6265SDimitry Andric     }
140181ad6265SDimitry Andric 
140281ad6265SDimitry Andric     SVal VisitUnarySymExpr(const UnarySymExpr *S) {
140381ad6265SDimitry Andric       auto I = Cached.find(S);
140481ad6265SDimitry Andric       if (I != Cached.end())
140581ad6265SDimitry Andric         return I->second;
140681ad6265SDimitry Andric       SVal Op = getConstOrVisit(S->getOperand());
140781ad6265SDimitry Andric       if (isUnchanged(S->getOperand(), Op))
140881ad6265SDimitry Andric         return skip(S);
140981ad6265SDimitry Andric 
141081ad6265SDimitry Andric       return cache(
141181ad6265SDimitry Andric           S, SVB.evalUnaryOp(State, S->getOpcode(), Op, S->getType()));
141281ad6265SDimitry Andric     }
141381ad6265SDimitry Andric 
14140b57cec5SDimitry Andric     SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
14150b57cec5SDimitry Andric 
14160b57cec5SDimitry Andric     SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
14170b57cec5SDimitry Andric 
14185f757f3fSDimitry Andric     SVal VisitSymbolVal(nonloc::SymbolVal V) {
14190b57cec5SDimitry Andric       // Simplification is much more costly than computing complexity.
14200b57cec5SDimitry Andric       // For high complexity, it may be not worth it.
14210b57cec5SDimitry Andric       return Visit(V.getSymbol());
14220b57cec5SDimitry Andric     }
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric     SVal VisitSVal(SVal V) { return V; }
14250b57cec5SDimitry Andric   };
14260b57cec5SDimitry Andric 
14270b57cec5SDimitry Andric   SVal SimplifiedV = Simplifier(State).Visit(V);
14280b57cec5SDimitry Andric   return SimplifiedV;
14290b57cec5SDimitry Andric }
1430