1fa0734ecSArgyrios Kyrtzidis // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*- 2fa0734ecSArgyrios Kyrtzidis // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6fa0734ecSArgyrios Kyrtzidis // 7fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 8fa0734ecSArgyrios Kyrtzidis // 9fa0734ecSArgyrios Kyrtzidis // This file defines SimpleSValBuilder, a basic implementation of SValBuilder. 10fa0734ecSArgyrios Kyrtzidis // 11fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 12fa0734ecSArgyrios Kyrtzidis 13f8cbac4bSTed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 143a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h" 15d70ec366SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 16001fd5b4STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 1712294f8dSArtem Dergachev #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h" 18fa0734ecSArgyrios Kyrtzidis 19fa0734ecSArgyrios Kyrtzidis using namespace clang; 20fa0734ecSArgyrios Kyrtzidis using namespace ento; 21fa0734ecSArgyrios Kyrtzidis 22fa0734ecSArgyrios Kyrtzidis namespace { 23fa0734ecSArgyrios Kyrtzidis class SimpleSValBuilder : public SValBuilder { 24978431e8SGabor Marton 25978431e8SGabor Marton // With one `simplifySValOnce` call, a compound symbols might collapse to 26978431e8SGabor Marton // simpler symbol tree that is still possible to further simplify. Thus, we 27978431e8SGabor Marton // do the simplification on a new symbol tree until we reach the simplest 28978431e8SGabor Marton // form, i.e. the fixpoint. 29978431e8SGabor Marton // Consider the following symbol `(b * b) * b * b` which has this tree: 30978431e8SGabor Marton // * 31978431e8SGabor Marton // / \ 32978431e8SGabor Marton // * b 33978431e8SGabor Marton // / \ 34978431e8SGabor Marton // / b 35978431e8SGabor Marton // (b * b) 36978431e8SGabor Marton // Now, if the `b * b == 1` new constraint is added then during the first 37978431e8SGabor Marton // iteration we have the following transformations: 38978431e8SGabor Marton // * * 39978431e8SGabor Marton // / \ / \ 40978431e8SGabor Marton // * b --> b b 41978431e8SGabor Marton // / \ 42978431e8SGabor Marton // / b 43978431e8SGabor Marton // 1 44978431e8SGabor Marton // We need another iteration to reach the final result `1`. 45978431e8SGabor Marton SVal simplifyUntilFixpoint(ProgramStateRef State, SVal Val); 46978431e8SGabor Marton 47978431e8SGabor Marton // Recursively descends into symbolic expressions and replaces symbols 48978431e8SGabor Marton // with their known values (in the sense of the getKnownValue() method). 49978431e8SGabor Marton // We traverse the symbol tree and query the constraint values for the 50978431e8SGabor Marton // sub-trees and if a value is a constant we do the constant folding. 51978431e8SGabor Marton SVal simplifySValOnce(ProgramStateRef State, SVal V); 52978431e8SGabor Marton 53fa0734ecSArgyrios Kyrtzidis public: 54fa0734ecSArgyrios Kyrtzidis SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context, 55001fd5b4STed Kremenek ProgramStateManager &stateMgr) 56fa0734ecSArgyrios Kyrtzidis : SValBuilder(alloc, context, stateMgr) {} 57637d1e66SAngel Garcia Gomez ~SimpleSValBuilder() override {} 58fa0734ecSArgyrios Kyrtzidis 59fb6b25b5SCraig Topper SVal evalMinus(NonLoc val) override; 60fb6b25b5SCraig Topper SVal evalComplement(NonLoc val) override; 61fb6b25b5SCraig Topper SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, 62fb6b25b5SCraig Topper NonLoc lhs, NonLoc rhs, QualType resultTy) override; 63fb6b25b5SCraig Topper SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op, 64fb6b25b5SCraig Topper Loc lhs, Loc rhs, QualType resultTy) override; 65fb6b25b5SCraig Topper SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op, 66fb6b25b5SCraig Topper Loc lhs, NonLoc rhs, QualType resultTy) override; 67fa0734ecSArgyrios Kyrtzidis 68fa0734ecSArgyrios Kyrtzidis /// getKnownValue - evaluates a given SVal. If the SVal has only one possible 69fa0734ecSArgyrios Kyrtzidis /// (integer) value, that value is returned. Otherwise, returns NULL. 70fb6b25b5SCraig Topper const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override; 71fa0734ecSArgyrios Kyrtzidis 7212294f8dSArtem Dergachev SVal simplifySVal(ProgramStateRef State, SVal V) override; 7312294f8dSArtem Dergachev 74fa0734ecSArgyrios Kyrtzidis SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op, 75fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &RHS, QualType resultTy); 76fa0734ecSArgyrios Kyrtzidis }; 77fa0734ecSArgyrios Kyrtzidis } // end anonymous namespace 78fa0734ecSArgyrios Kyrtzidis 79fa0734ecSArgyrios Kyrtzidis SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc, 80fa0734ecSArgyrios Kyrtzidis ASTContext &context, 81001fd5b4STed Kremenek ProgramStateManager &stateMgr) { 82fa0734ecSArgyrios Kyrtzidis return new SimpleSValBuilder(alloc, context, stateMgr); 83fa0734ecSArgyrios Kyrtzidis } 84fa0734ecSArgyrios Kyrtzidis 85fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 86fa0734ecSArgyrios Kyrtzidis // Transfer function for unary operators. 87fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 88fa0734ecSArgyrios Kyrtzidis 89fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalMinus(NonLoc val) { 90fa0734ecSArgyrios Kyrtzidis switch (val.getSubKind()) { 91fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: 922fdacbc5SDavid Blaikie return val.castAs<nonloc::ConcreteInt>().evalMinus(*this); 93b5b2aec1SGabor Marton case nonloc::SymbolValKind: 94b5b2aec1SGabor Marton return makeNonLoc(val.castAs<nonloc::SymbolVal>().getSymbol(), UO_Minus, 95b5b2aec1SGabor Marton val.getType(Context)); 96fa0734ecSArgyrios Kyrtzidis default: 97fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 98fa0734ecSArgyrios Kyrtzidis } 99fa0734ecSArgyrios Kyrtzidis } 100fa0734ecSArgyrios Kyrtzidis 101fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalComplement(NonLoc X) { 102fa0734ecSArgyrios Kyrtzidis switch (X.getSubKind()) { 103fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: 1042fdacbc5SDavid Blaikie return X.castAs<nonloc::ConcreteInt>().evalComplement(*this); 105b5b2aec1SGabor Marton case nonloc::SymbolValKind: 106b5b2aec1SGabor Marton return makeNonLoc(X.castAs<nonloc::SymbolVal>().getSymbol(), UO_Not, 107b5b2aec1SGabor Marton X.getType(Context)); 108fa0734ecSArgyrios Kyrtzidis default: 109fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 110fa0734ecSArgyrios Kyrtzidis } 111fa0734ecSArgyrios Kyrtzidis } 112fa0734ecSArgyrios Kyrtzidis 11314742443STomasz Kamiński // Checks if the negation the value and flipping sign preserve 11414742443STomasz Kamiński // the semantics on the operation in the resultType 11514742443STomasz Kamiński static bool isNegationValuePreserving(const llvm::APSInt &Value, 11614742443STomasz Kamiński APSIntType ResultType) { 11714742443STomasz Kamiński const unsigned ValueBits = Value.getSignificantBits(); 11814742443STomasz Kamiński if (ValueBits == ResultType.getBitWidth()) { 11914742443STomasz Kamiński // The value is the lowest negative value that is representable 12014742443STomasz Kamiński // in signed integer with bitWith of result type. The 12114742443STomasz Kamiński // negation is representable if resultType is unsigned. 12214742443STomasz Kamiński return ResultType.isUnsigned(); 12314742443STomasz Kamiński } 12414742443STomasz Kamiński 12514742443STomasz Kamiński // If resultType bitWith is higher that number of bits required 12614742443STomasz Kamiński // to represent RHS, the sign flip produce same value. 12714742443STomasz Kamiński return ValueBits < ResultType.getBitWidth(); 12814742443STomasz Kamiński } 12914742443STomasz Kamiński 130fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 131fa0734ecSArgyrios Kyrtzidis // Transfer function for binary operators. 132fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 133fa0734ecSArgyrios Kyrtzidis 134fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS, 135fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 136fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &RHS, 137fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 138fa0734ecSArgyrios Kyrtzidis bool isIdempotent = false; 139fa0734ecSArgyrios Kyrtzidis 140fa0734ecSArgyrios Kyrtzidis // Check for a few special cases with known reductions first. 141fa0734ecSArgyrios Kyrtzidis switch (op) { 142fa0734ecSArgyrios Kyrtzidis default: 143fa0734ecSArgyrios Kyrtzidis // We can't reduce this case; just treat it normally. 144fa0734ecSArgyrios Kyrtzidis break; 145fa0734ecSArgyrios Kyrtzidis case BO_Mul: 146fa0734ecSArgyrios Kyrtzidis // a*0 and a*1 147fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 148fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 149fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 150fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 151fa0734ecSArgyrios Kyrtzidis break; 152fa0734ecSArgyrios Kyrtzidis case BO_Div: 153fa0734ecSArgyrios Kyrtzidis // a/0 and a/1 154fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 155fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere. 156fa0734ecSArgyrios Kyrtzidis return UndefinedVal(); 157fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 158fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 159fa0734ecSArgyrios Kyrtzidis break; 160fa0734ecSArgyrios Kyrtzidis case BO_Rem: 161fa0734ecSArgyrios Kyrtzidis // a%0 and a%1 162fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 163fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere. 164fa0734ecSArgyrios Kyrtzidis return UndefinedVal(); 165fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 166fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 167fa0734ecSArgyrios Kyrtzidis break; 168fa0734ecSArgyrios Kyrtzidis case BO_Add: 169fa0734ecSArgyrios Kyrtzidis case BO_Sub: 170fa0734ecSArgyrios Kyrtzidis case BO_Shl: 171fa0734ecSArgyrios Kyrtzidis case BO_Shr: 172fa0734ecSArgyrios Kyrtzidis case BO_Xor: 173fa0734ecSArgyrios Kyrtzidis // a+0, a-0, a<<0, a>>0, a^0 174fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 175fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 176fa0734ecSArgyrios Kyrtzidis break; 177fa0734ecSArgyrios Kyrtzidis case BO_And: 178fa0734ecSArgyrios Kyrtzidis // a&0 and a&(~0) 179fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 180fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 181d933adeaSJay Foad else if (RHS.isAllOnes()) 182fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 183fa0734ecSArgyrios Kyrtzidis break; 184fa0734ecSArgyrios Kyrtzidis case BO_Or: 185fa0734ecSArgyrios Kyrtzidis // a|0 and a|(~0) 186fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 187fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 188d933adeaSJay Foad else if (RHS.isAllOnes()) { 189fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS); 190fa0734ecSArgyrios Kyrtzidis return nonloc::ConcreteInt(Result); 191fa0734ecSArgyrios Kyrtzidis } 192fa0734ecSArgyrios Kyrtzidis break; 193fa0734ecSArgyrios Kyrtzidis } 194fa0734ecSArgyrios Kyrtzidis 195fa0734ecSArgyrios Kyrtzidis // Idempotent ops (like a*1) can still change the type of an expression. 19601ddfa95SDenys Petrov // Wrap the LHS up in a NonLoc again and let evalCast do the 1975ad574c0SZhanyong Wan // dirty work. 198d066f79cSAnna Zaks if (isIdempotent) 19901ddfa95SDenys Petrov return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{}); 200fa0734ecSArgyrios Kyrtzidis 201fa0734ecSArgyrios Kyrtzidis // If we reach this point, the expression cannot be simplified. 20254569448SJordy Rose // Make a SymbolVal for the entire expression, after converting the RHS. 20354569448SJordy Rose const llvm::APSInt *ConvertedRHS = &RHS; 20454569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) { 20554569448SJordy Rose // We're looking for a type big enough to compare the symbolic value 20654569448SJordy Rose // with the given constant. 20754569448SJordy Rose // FIXME: This is an approximation of Sema::UsualArithmeticConversions. 20854569448SJordy Rose ASTContext &Ctx = getContext(); 209a808e165STed Kremenek QualType SymbolType = LHS->getType(); 21054569448SJordy Rose uint64_t ValWidth = RHS.getBitWidth(); 21154569448SJordy Rose uint64_t TypeWidth = Ctx.getTypeSize(SymbolType); 21254569448SJordy Rose 21354569448SJordy Rose if (ValWidth < TypeWidth) { 21454569448SJordy Rose // If the value is too small, extend it. 21554569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS); 21654569448SJordy Rose } else if (ValWidth == TypeWidth) { 21754569448SJordy Rose // If the value is signed but the symbol is unsigned, do the comparison 21854569448SJordy Rose // in unsigned space. [C99 6.3.1.8] 21954569448SJordy Rose // (For the opposite case, the value is already unsigned.) 22054569448SJordy Rose if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType()) 22154569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS); 22254569448SJordy Rose } 22314742443STomasz Kamiński } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) { 22414742443STomasz Kamiński // Change a+(-N) into a-N, and a-(-N) into a+N 22514742443STomasz Kamiński // Adjust addition/subtraction of negative value, to 22614742443STomasz Kamiński // subtraction/addition of the negated value. 22714742443STomasz Kamiński APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy); 22814742443STomasz Kamiński if (isNegationValuePreserving(RHS, resultIntTy)) { 22914742443STomasz Kamiński ConvertedRHS = &BasicVals.getValue(-resultIntTy.convert(RHS)); 23014742443STomasz Kamiński op = (op == BO_Add) ? BO_Sub : BO_Add; 23114742443STomasz Kamiński } else { 23214742443STomasz Kamiński ConvertedRHS = &BasicVals.Convert(resultTy, RHS); 23314742443STomasz Kamiński } 234da5b5ae8SBalazs Benics } else 23554569448SJordy Rose ConvertedRHS = &BasicVals.Convert(resultTy, RHS); 23654569448SJordy Rose 23754569448SJordy Rose return makeNonLoc(LHS, op, *ConvertedRHS, resultTy); 238fa0734ecSArgyrios Kyrtzidis } 239fa0734ecSArgyrios Kyrtzidis 2402bbccca9SAdam Balogh // See if Sym is known to be a relation Rel with Bound. 2412bbccca9SAdam Balogh static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym, 2422bbccca9SAdam Balogh llvm::APSInt Bound, ProgramStateRef State) { 2432bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 2442bbccca9SAdam Balogh SVal Result = 2452bbccca9SAdam Balogh SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym), 2462bbccca9SAdam Balogh nonloc::ConcreteInt(Bound), SVB.getConditionType()); 2472bbccca9SAdam Balogh if (auto DV = Result.getAs<DefinedSVal>()) { 2482bbccca9SAdam Balogh return !State->assume(*DV, false); 2492bbccca9SAdam Balogh } 2502bbccca9SAdam Balogh return false; 2512bbccca9SAdam Balogh } 2522bbccca9SAdam Balogh 2532bbccca9SAdam Balogh // See if Sym is known to be within [min/4, max/4], where min and max 2542bbccca9SAdam Balogh // are the bounds of the symbol's integral type. With such symbols, 2552bbccca9SAdam Balogh // some manipulations can be performed without the risk of overflow. 2562bbccca9SAdam Balogh // assume() doesn't cause infinite recursion because we should be dealing 2572bbccca9SAdam Balogh // with simpler symbols on every recursive call. 2582bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(SymbolRef Sym, 2592bbccca9SAdam Balogh ProgramStateRef State) { 2602bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 2612bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory(); 2622bbccca9SAdam Balogh 2632bbccca9SAdam Balogh QualType T = Sym->getType(); 2642bbccca9SAdam Balogh assert(T->isSignedIntegerOrEnumerationType() && 2652bbccca9SAdam Balogh "This only works with signed integers!"); 2662bbccca9SAdam Balogh APSIntType AT = BV.getAPSIntType(T); 2672bbccca9SAdam Balogh 2682bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max; 2692bbccca9SAdam Balogh return isInRelation(BO_LE, Sym, Max, State) && 2702bbccca9SAdam Balogh isInRelation(BO_GE, Sym, Min, State); 2712bbccca9SAdam Balogh } 2722bbccca9SAdam Balogh 2732bbccca9SAdam Balogh // Same for the concrete integers: see if I is within [min/4, max/4]. 2742bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(llvm::APSInt I) { 2752bbccca9SAdam Balogh APSIntType AT(I); 2762bbccca9SAdam Balogh assert(!AT.isUnsigned() && 2772bbccca9SAdam Balogh "This only works with signed integers!"); 2782bbccca9SAdam Balogh 2792bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max; 2802bbccca9SAdam Balogh return (I <= Max) && (I >= -Max); 2812bbccca9SAdam Balogh } 2822bbccca9SAdam Balogh 2832bbccca9SAdam Balogh static std::pair<SymbolRef, llvm::APSInt> 2842bbccca9SAdam Balogh decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) { 2852bbccca9SAdam Balogh if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym)) 2862bbccca9SAdam Balogh if (BinaryOperator::isAdditiveOp(SymInt->getOpcode())) 2872bbccca9SAdam Balogh return std::make_pair(SymInt->getLHS(), 2882bbccca9SAdam Balogh (SymInt->getOpcode() == BO_Add) ? 2892bbccca9SAdam Balogh (SymInt->getRHS()) : 2902bbccca9SAdam Balogh (-SymInt->getRHS())); 2912bbccca9SAdam Balogh 2922bbccca9SAdam Balogh // Fail to decompose: "reduce" the problem to the "$x + 0" case. 2932bbccca9SAdam Balogh return std::make_pair(Sym, BV.getValue(0, Sym->getType())); 2942bbccca9SAdam Balogh } 2952bbccca9SAdam Balogh 2962bbccca9SAdam Balogh // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the 2972bbccca9SAdam Balogh // same signed integral type and no overflows occur (which should be checked 2982bbccca9SAdam Balogh // by the caller). 2992bbccca9SAdam Balogh static NonLoc doRearrangeUnchecked(ProgramStateRef State, 3002bbccca9SAdam Balogh BinaryOperator::Opcode Op, 3012bbccca9SAdam Balogh SymbolRef LSym, llvm::APSInt LInt, 3022bbccca9SAdam Balogh SymbolRef RSym, llvm::APSInt RInt) { 3032bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 3042bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory(); 3052bbccca9SAdam Balogh SymbolManager &SymMgr = SVB.getSymbolManager(); 3062bbccca9SAdam Balogh 3072bbccca9SAdam Balogh QualType SymTy = LSym->getType(); 3082bbccca9SAdam Balogh assert(SymTy == RSym->getType() && 3092bbccca9SAdam Balogh "Symbols are not of the same type!"); 3102bbccca9SAdam Balogh assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) && 3112bbccca9SAdam Balogh "Integers are not of the same type as symbols!"); 3122bbccca9SAdam Balogh assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) && 3132bbccca9SAdam Balogh "Integers are not of the same type as symbols!"); 3142bbccca9SAdam Balogh 3152bbccca9SAdam Balogh QualType ResultTy; 3162bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op)) 3172bbccca9SAdam Balogh ResultTy = SVB.getConditionType(); 3182bbccca9SAdam Balogh else if (BinaryOperator::isAdditiveOp(Op)) 3192bbccca9SAdam Balogh ResultTy = SymTy; 3202bbccca9SAdam Balogh else 3212bbccca9SAdam Balogh llvm_unreachable("Operation not suitable for unchecked rearrangement!"); 3222bbccca9SAdam Balogh 3232bbccca9SAdam Balogh // FIXME: Can we use assume() without getting into an infinite recursion? 3242bbccca9SAdam Balogh if (LSym == RSym) 3252bbccca9SAdam Balogh return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt), 3262bbccca9SAdam Balogh nonloc::ConcreteInt(RInt), ResultTy) 3272bbccca9SAdam Balogh .castAs<NonLoc>(); 3282bbccca9SAdam Balogh 3292bbccca9SAdam Balogh SymbolRef ResultSym = nullptr; 3302bbccca9SAdam Balogh BinaryOperator::Opcode ResultOp; 3312bbccca9SAdam Balogh llvm::APSInt ResultInt; 3322bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op)) { 3332bbccca9SAdam Balogh // Prefer comparing to a non-negative number. 3342bbccca9SAdam Balogh // FIXME: Maybe it'd be better to have consistency in 3352bbccca9SAdam Balogh // "$x - $y" vs. "$y - $x" because those are solver's keys. 3362bbccca9SAdam Balogh if (LInt > RInt) { 3372bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy); 3382bbccca9SAdam Balogh ResultOp = BinaryOperator::reverseComparisonOp(Op); 3392bbccca9SAdam Balogh ResultInt = LInt - RInt; // Opposite order! 3402bbccca9SAdam Balogh } else { 3412bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy); 3422bbccca9SAdam Balogh ResultOp = Op; 3432bbccca9SAdam Balogh ResultInt = RInt - LInt; // Opposite order! 3442bbccca9SAdam Balogh } 3452bbccca9SAdam Balogh } else { 3462bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy); 3472bbccca9SAdam Balogh ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt); 3482bbccca9SAdam Balogh ResultOp = BO_Add; 3492bbccca9SAdam Balogh // Bring back the cosmetic difference. 3502bbccca9SAdam Balogh if (ResultInt < 0) { 3512bbccca9SAdam Balogh ResultInt = -ResultInt; 3522bbccca9SAdam Balogh ResultOp = BO_Sub; 3532bbccca9SAdam Balogh } else if (ResultInt == 0) { 3542bbccca9SAdam Balogh // Shortcut: Simplify "$x + 0" to "$x". 3552bbccca9SAdam Balogh return nonloc::SymbolVal(ResultSym); 3562bbccca9SAdam Balogh } 3572bbccca9SAdam Balogh } 3582bbccca9SAdam Balogh const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt); 3592bbccca9SAdam Balogh return nonloc::SymbolVal( 3602bbccca9SAdam Balogh SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy)); 3612bbccca9SAdam Balogh } 3622bbccca9SAdam Balogh 3632bbccca9SAdam Balogh // Rearrange if symbol type matches the result type and if the operator is a 3642bbccca9SAdam Balogh // comparison operator, both symbol and constant must be within constant 3652bbccca9SAdam Balogh // overflow bounds. 3662bbccca9SAdam Balogh static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op, 3672bbccca9SAdam Balogh SymbolRef Sym, llvm::APSInt Int, QualType Ty) { 3682bbccca9SAdam Balogh return Sym->getType() == Ty && 3692bbccca9SAdam Balogh (!BinaryOperator::isComparisonOp(Op) || 3702bbccca9SAdam Balogh (isWithinConstantOverflowBounds(Sym, State) && 3712bbccca9SAdam Balogh isWithinConstantOverflowBounds(Int))); 3722bbccca9SAdam Balogh } 3732bbccca9SAdam Balogh 3742bbccca9SAdam Balogh static Optional<NonLoc> tryRearrange(ProgramStateRef State, 3752bbccca9SAdam Balogh BinaryOperator::Opcode Op, NonLoc Lhs, 3762bbccca9SAdam Balogh NonLoc Rhs, QualType ResultTy) { 3772bbccca9SAdam Balogh ProgramStateManager &StateMgr = State->getStateManager(); 3782bbccca9SAdam Balogh SValBuilder &SVB = StateMgr.getSValBuilder(); 3792bbccca9SAdam Balogh 3802bbccca9SAdam Balogh // We expect everything to be of the same type - this type. 3812bbccca9SAdam Balogh QualType SingleTy; 3822bbccca9SAdam Balogh 383dcde8accSAdam Balogh // FIXME: After putting complexity threshold to the symbols we can always 384dcde8accSAdam Balogh // rearrange additive operations but rearrange comparisons only if 385dcde8accSAdam Balogh // option is set. 386b97a9640SBalazs Benics if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation) 387dcde8accSAdam Balogh return None; 388dcde8accSAdam Balogh 3892bbccca9SAdam Balogh SymbolRef LSym = Lhs.getAsSymbol(); 3902bbccca9SAdam Balogh if (!LSym) 3912bbccca9SAdam Balogh return None; 3922bbccca9SAdam Balogh 393dcde8accSAdam Balogh if (BinaryOperator::isComparisonOp(Op)) { 3942bbccca9SAdam Balogh SingleTy = LSym->getType(); 3952bbccca9SAdam Balogh if (ResultTy != SVB.getConditionType()) 3962bbccca9SAdam Balogh return None; 3972bbccca9SAdam Balogh // Initialize SingleTy later with a symbol's type. 3982bbccca9SAdam Balogh } else if (BinaryOperator::isAdditiveOp(Op)) { 3992bbccca9SAdam Balogh SingleTy = ResultTy; 40013e186c0SAdam Balogh if (LSym->getType() != SingleTy) 40113e186c0SAdam Balogh return None; 4022bbccca9SAdam Balogh } else { 4032bbccca9SAdam Balogh // Don't rearrange other operations. 4042bbccca9SAdam Balogh return None; 4052bbccca9SAdam Balogh } 4062bbccca9SAdam Balogh 4072bbccca9SAdam Balogh assert(!SingleTy.isNull() && "We should have figured out the type by now!"); 4082bbccca9SAdam Balogh 409471d0864SAdam Balogh // Rearrange signed symbolic expressions only 410471d0864SAdam Balogh if (!SingleTy->isSignedIntegerOrEnumerationType()) 411471d0864SAdam Balogh return None; 412471d0864SAdam Balogh 4132bbccca9SAdam Balogh SymbolRef RSym = Rhs.getAsSymbol(); 4142bbccca9SAdam Balogh if (!RSym || RSym->getType() != SingleTy) 4152bbccca9SAdam Balogh return None; 4162bbccca9SAdam Balogh 4172bbccca9SAdam Balogh BasicValueFactory &BV = State->getBasicVals(); 4182bbccca9SAdam Balogh llvm::APSInt LInt, RInt; 4192bbccca9SAdam Balogh std::tie(LSym, LInt) = decomposeSymbol(LSym, BV); 4202bbccca9SAdam Balogh std::tie(RSym, RInt) = decomposeSymbol(RSym, BV); 4212bbccca9SAdam Balogh if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) || 4222bbccca9SAdam Balogh !shouldRearrange(State, Op, RSym, RInt, SingleTy)) 4232bbccca9SAdam Balogh return None; 4242bbccca9SAdam Balogh 4252bbccca9SAdam Balogh // We know that no overflows can occur anymore. 4262bbccca9SAdam Balogh return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt); 4272bbccca9SAdam Balogh } 4282bbccca9SAdam Balogh 42949b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state, 430fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 431fa0734ecSArgyrios Kyrtzidis NonLoc lhs, NonLoc rhs, 432fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 433f0e9ca86SAnna Zaks NonLoc InputLHS = lhs; 434f0e9ca86SAnna Zaks NonLoc InputRHS = rhs; 435f0e9ca86SAnna Zaks 43612887a20SGabor Marton // Constraints may have changed since the creation of a bound SVal. Check if 43712887a20SGabor Marton // the values can be simplified based on those new constraints. 43812887a20SGabor Marton SVal simplifiedLhs = simplifySVal(state, lhs); 43912887a20SGabor Marton SVal simplifiedRhs = simplifySVal(state, rhs); 44012887a20SGabor Marton if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) 44112887a20SGabor Marton lhs = *simplifiedLhsAsNonLoc; 44212887a20SGabor Marton if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>()) 44312887a20SGabor Marton rhs = *simplifiedRhsAsNonLoc; 44412887a20SGabor Marton 445fa0734ecSArgyrios Kyrtzidis // Handle trivial case where left-side and right-side are the same. 446fa0734ecSArgyrios Kyrtzidis if (lhs == rhs) 447fa0734ecSArgyrios Kyrtzidis switch (op) { 448fa0734ecSArgyrios Kyrtzidis default: 449fa0734ecSArgyrios Kyrtzidis break; 450fa0734ecSArgyrios Kyrtzidis case BO_EQ: 451fa0734ecSArgyrios Kyrtzidis case BO_LE: 452fa0734ecSArgyrios Kyrtzidis case BO_GE: 453fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 454fa0734ecSArgyrios Kyrtzidis case BO_LT: 455fa0734ecSArgyrios Kyrtzidis case BO_GT: 456fa0734ecSArgyrios Kyrtzidis case BO_NE: 457fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 458fa0734ecSArgyrios Kyrtzidis case BO_Xor: 459fa0734ecSArgyrios Kyrtzidis case BO_Sub: 4607523d1a8SJordan Rose if (resultTy->isIntegralOrEnumerationType()) 461fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 46201ddfa95SDenys Petrov return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy, 46301ddfa95SDenys Petrov QualType{}); 464fa0734ecSArgyrios Kyrtzidis case BO_Or: 465fa0734ecSArgyrios Kyrtzidis case BO_And: 46601ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 467fa0734ecSArgyrios Kyrtzidis } 468fa0734ecSArgyrios Kyrtzidis 46940446663SKazu Hirata while (true) { 470fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) { 471fa0734ecSArgyrios Kyrtzidis default: 472bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, lhs, rhs, resultTy); 47364c01f7bSDevin Coughlin case nonloc::PointerToMemberKind: { 47464c01f7bSDevin Coughlin assert(rhs.getSubKind() == nonloc::PointerToMemberKind && 47564c01f7bSDevin Coughlin "Both SVals should have pointer-to-member-type"); 47664c01f7bSDevin Coughlin auto LPTM = lhs.castAs<nonloc::PointerToMember>(), 47764c01f7bSDevin Coughlin RPTM = rhs.castAs<nonloc::PointerToMember>(); 47864c01f7bSDevin Coughlin auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData(); 47964c01f7bSDevin Coughlin switch (op) { 48064c01f7bSDevin Coughlin case BO_EQ: 48164c01f7bSDevin Coughlin return makeTruthVal(LPTMD == RPTMD, resultTy); 48264c01f7bSDevin Coughlin case BO_NE: 48364c01f7bSDevin Coughlin return makeTruthVal(LPTMD != RPTMD, resultTy); 48464c01f7bSDevin Coughlin default: 48564c01f7bSDevin Coughlin return UnknownVal(); 48664c01f7bSDevin Coughlin } 48764c01f7bSDevin Coughlin } 488fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind: { 4892fdacbc5SDavid Blaikie Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc(); 490fa0734ecSArgyrios Kyrtzidis switch (rhs.getSubKind()) { 491fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind: 49218d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation 49318d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete. 49418d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op)) 49518d77984SAlexander Shaposhnikov return UnknownVal(); 496fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL, 4972fdacbc5SDavid Blaikie rhs.castAs<nonloc::LocAsInteger>().getLoc(), 498fa0734ecSArgyrios Kyrtzidis resultTy); 499fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: { 50018d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation 50118d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete. 50218d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op)) 50318d77984SAlexander Shaposhnikov return UnknownVal(); 504fa0734ecSArgyrios Kyrtzidis // Transform the integer into a location and compare. 5057333a9eaSArtem Dergachev // FIXME: This only makes sense for comparisons. If we want to, say, 5067333a9eaSArtem Dergachev // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it, 5077333a9eaSArtem Dergachev // then pack it back into a LocAsInteger. 5082fdacbc5SDavid Blaikie llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue(); 50927ed855aSDavid Stenberg // If the region has a symbolic base, pay attention to the type; it 51027ed855aSDavid Stenberg // might be coming from a non-default address space. For non-symbolic 51127ed855aSDavid Stenberg // regions it doesn't matter that much because such comparisons would 51227ed855aSDavid Stenberg // most likely evaluate to concrete false anyway. FIXME: We might 51327ed855aSDavid Stenberg // still need to handle the non-comparison case. 51427ed855aSDavid Stenberg if (SymbolRef lSym = lhs.getAsLocSymbol(true)) 51527ed855aSDavid Stenberg BasicVals.getAPSIntType(lSym->getType()).apply(i); 51627ed855aSDavid Stenberg else 5177e3c3ea3SJordy Rose BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i); 518fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy); 519fa0734ecSArgyrios Kyrtzidis } 520fa0734ecSArgyrios Kyrtzidis default: 521fa0734ecSArgyrios Kyrtzidis switch (op) { 522fa0734ecSArgyrios Kyrtzidis case BO_EQ: 523fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 524fa0734ecSArgyrios Kyrtzidis case BO_NE: 525fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 526fa0734ecSArgyrios Kyrtzidis default: 527fa0734ecSArgyrios Kyrtzidis // This case also handles pointer arithmetic. 528bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 529fa0734ecSArgyrios Kyrtzidis } 530fa0734ecSArgyrios Kyrtzidis } 531fa0734ecSArgyrios Kyrtzidis } 532d066f79cSAnna Zaks case nonloc::ConcreteIntKind: { 5332fdacbc5SDavid Blaikie llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue(); 534d066f79cSAnna Zaks 53554569448SJordy Rose // If we're dealing with two known constants, just perform the operation. 53654569448SJordy Rose if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) { 53754569448SJordy Rose llvm::APSInt RHSValue = *KnownRHSValue; 53854569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) { 53954569448SJordy Rose // We're looking for a type big enough to compare the two values. 5407e3c3ea3SJordy Rose // FIXME: This is not correct. char + short will result in a promotion 5417e3c3ea3SJordy Rose // to int. Unfortunately we have lost types by this point. 5427e3c3ea3SJordy Rose APSIntType CompareType = std::max(APSIntType(LHSValue), 5437e3c3ea3SJordy Rose APSIntType(RHSValue)); 5447e3c3ea3SJordy Rose CompareType.apply(LHSValue); 5457e3c3ea3SJordy Rose CompareType.apply(RHSValue); 54654569448SJordy Rose } else if (!BinaryOperator::isShiftOp(op)) { 5477e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy); 5487e3c3ea3SJordy Rose IntType.apply(LHSValue); 5497e3c3ea3SJordy Rose IntType.apply(RHSValue); 550d066f79cSAnna Zaks } 551d066f79cSAnna Zaks 55254569448SJordy Rose const llvm::APSInt *Result = 55354569448SJordy Rose BasicVals.evalAPSInt(op, LHSValue, RHSValue); 55454569448SJordy Rose if (!Result) 55554569448SJordy Rose return UndefinedVal(); 55654569448SJordy Rose 55754569448SJordy Rose return nonloc::ConcreteInt(*Result); 55854569448SJordy Rose } 559d066f79cSAnna Zaks 560d066f79cSAnna Zaks // Swap the left and right sides and flip the operator if doing so 561d066f79cSAnna Zaks // allows us to better reason about the expression (this is a form 562d066f79cSAnna Zaks // of expression canonicalization). 563d066f79cSAnna Zaks // While we're at it, catch some special cases for non-commutative ops. 564d066f79cSAnna Zaks switch (op) { 565d066f79cSAnna Zaks case BO_LT: 566d066f79cSAnna Zaks case BO_GT: 567d066f79cSAnna Zaks case BO_LE: 568d066f79cSAnna Zaks case BO_GE: 569604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op); 5704dc0b1acSReid Kleckner LLVM_FALLTHROUGH; 571d066f79cSAnna Zaks case BO_EQ: 572d066f79cSAnna Zaks case BO_NE: 573d066f79cSAnna Zaks case BO_Add: 574d066f79cSAnna Zaks case BO_Mul: 575d066f79cSAnna Zaks case BO_And: 576d066f79cSAnna Zaks case BO_Xor: 577d066f79cSAnna Zaks case BO_Or: 57854569448SJordy Rose std::swap(lhs, rhs); 579d066f79cSAnna Zaks continue; 580d066f79cSAnna Zaks case BO_Shr: 58154569448SJordy Rose // (~0)>>a 582d933adeaSJay Foad if (LHSValue.isAllOnes() && LHSValue.isSigned()) 58301ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 5844dc0b1acSReid Kleckner LLVM_FALLTHROUGH; 585d066f79cSAnna Zaks case BO_Shl: 58654569448SJordy Rose // 0<<a and 0>>a 58754569448SJordy Rose if (LHSValue == 0) 58801ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 589bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 590015c3988SGabor Marton case BO_Div: 591015c3988SGabor Marton // 0 / x == 0 59273c120a9SValeriy Savchenko case BO_Rem: 59373c120a9SValeriy Savchenko // 0 % x == 0 59473c120a9SValeriy Savchenko if (LHSValue == 0) 59573c120a9SValeriy Savchenko return makeZeroVal(resultTy); 59673c120a9SValeriy Savchenko LLVM_FALLTHROUGH; 597d066f79cSAnna Zaks default: 598bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 599d066f79cSAnna Zaks } 600d066f79cSAnna Zaks } 601d066f79cSAnna Zaks case nonloc::SymbolValKind: { 60254569448SJordy Rose // We only handle LHS as simple symbols or SymIntExprs. 6032fdacbc5SDavid Blaikie SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol(); 604d066f79cSAnna Zaks 605d066f79cSAnna Zaks // LHS is a symbolic expression. 60654569448SJordy Rose if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) { 607fa0734ecSArgyrios Kyrtzidis 608fa0734ecSArgyrios Kyrtzidis // Is this a logical not? (!x is represented as x == 0.) 609fa0734ecSArgyrios Kyrtzidis if (op == BO_EQ && rhs.isZeroConstant()) { 610fa0734ecSArgyrios Kyrtzidis // We know how to negate certain expressions. Simplify them here. 611fa0734ecSArgyrios Kyrtzidis 612fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode opc = symIntExpr->getOpcode(); 613fa0734ecSArgyrios Kyrtzidis switch (opc) { 614fa0734ecSArgyrios Kyrtzidis default: 615fa0734ecSArgyrios Kyrtzidis // We don't know how to negate this operation. 616fa0734ecSArgyrios Kyrtzidis // Just handle it as if it were a normal comparison to 0. 617fa0734ecSArgyrios Kyrtzidis break; 618fa0734ecSArgyrios Kyrtzidis case BO_LAnd: 619fa0734ecSArgyrios Kyrtzidis case BO_LOr: 62083d382b1SDavid Blaikie llvm_unreachable("Logical operators handled by branching logic."); 621fa0734ecSArgyrios Kyrtzidis case BO_Assign: 622fa0734ecSArgyrios Kyrtzidis case BO_MulAssign: 623fa0734ecSArgyrios Kyrtzidis case BO_DivAssign: 624fa0734ecSArgyrios Kyrtzidis case BO_RemAssign: 625fa0734ecSArgyrios Kyrtzidis case BO_AddAssign: 626fa0734ecSArgyrios Kyrtzidis case BO_SubAssign: 627fa0734ecSArgyrios Kyrtzidis case BO_ShlAssign: 628fa0734ecSArgyrios Kyrtzidis case BO_ShrAssign: 629fa0734ecSArgyrios Kyrtzidis case BO_AndAssign: 630fa0734ecSArgyrios Kyrtzidis case BO_XorAssign: 631fa0734ecSArgyrios Kyrtzidis case BO_OrAssign: 632fa0734ecSArgyrios Kyrtzidis case BO_Comma: 63383d382b1SDavid Blaikie llvm_unreachable("'=' and ',' operators handled by ExprEngine."); 634fa0734ecSArgyrios Kyrtzidis case BO_PtrMemD: 635fa0734ecSArgyrios Kyrtzidis case BO_PtrMemI: 63683d382b1SDavid Blaikie llvm_unreachable("Pointer arithmetic not handled here."); 637fa0734ecSArgyrios Kyrtzidis case BO_LT: 638fa0734ecSArgyrios Kyrtzidis case BO_GT: 639fa0734ecSArgyrios Kyrtzidis case BO_LE: 640fa0734ecSArgyrios Kyrtzidis case BO_GE: 641fa0734ecSArgyrios Kyrtzidis case BO_EQ: 642fa0734ecSArgyrios Kyrtzidis case BO_NE: 643dc16628cSJordan Rose assert(resultTy->isBooleanType() || 644dc16628cSJordan Rose resultTy == getConditionType()); 645dc16628cSJordan Rose assert(symIntExpr->getType()->isBooleanType() || 646dc16628cSJordan Rose getContext().hasSameUnqualifiedType(symIntExpr->getType(), 647dc16628cSJordan Rose getConditionType())); 648fa0734ecSArgyrios Kyrtzidis // Negate the comparison and make a value. 649604d0bbbSJordan Rose opc = BinaryOperator::negateComparisonOp(opc); 650fa0734ecSArgyrios Kyrtzidis return makeNonLoc(symIntExpr->getLHS(), opc, 651fa0734ecSArgyrios Kyrtzidis symIntExpr->getRHS(), resultTy); 652fa0734ecSArgyrios Kyrtzidis } 653fa0734ecSArgyrios Kyrtzidis } 654fa0734ecSArgyrios Kyrtzidis 655fa0734ecSArgyrios Kyrtzidis // For now, only handle expressions whose RHS is a constant. 65654569448SJordy Rose if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) { 657fa0734ecSArgyrios Kyrtzidis // If both the LHS and the current expression are additive, 65854569448SJordy Rose // fold their constants and try again. 659fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(op)) { 660fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode lop = symIntExpr->getOpcode(); 661fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(lop)) { 66254569448SJordy Rose // Convert the two constants to a common type, then combine them. 66354569448SJordy Rose 664fa0734ecSArgyrios Kyrtzidis // resultTy may not be the best type to convert to, but it's 665fa0734ecSArgyrios Kyrtzidis // probably the best choice in expressions with mixed type 666fa0734ecSArgyrios Kyrtzidis // (such as x+1U+2LL). The rules for implicit conversions should 667fa0734ecSArgyrios Kyrtzidis // choose a reasonable type to preserve the expression, and will 668fa0734ecSArgyrios Kyrtzidis // at least match how the value is going to be used. 6697e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy); 6707e3c3ea3SJordy Rose const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS()); 6717e3c3ea3SJordy Rose const llvm::APSInt &second = IntType.convert(*RHSValue); 67254569448SJordy Rose 67314742443STomasz Kamiński // If the op and lop agrees, then we just need to 67414742443STomasz Kamiński // sum the constants. Otherwise, we change to operation 67514742443STomasz Kamiński // type if substraction would produce negative value 67614742443STomasz Kamiński // (and cause overflow for unsigned integers), 67714742443STomasz Kamiński // as consequence x+1U-10 produces x-9U, instead 67814742443STomasz Kamiński // of x+4294967287U, that would be produced without this 67914742443STomasz Kamiński // additional check. 680fa0734ecSArgyrios Kyrtzidis const llvm::APSInt *newRHS; 68114742443STomasz Kamiński if (lop == op) { 682fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Add, first, second); 68314742443STomasz Kamiński } else if (first >= second) { 684fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Sub, first, second); 68514742443STomasz Kamiński op = lop; 68614742443STomasz Kamiński } else { 68714742443STomasz Kamiński newRHS = BasicVals.evalAPSInt(BO_Sub, second, first); 68814742443STomasz Kamiński } 68954569448SJordy Rose 69054569448SJordy Rose assert(newRHS && "Invalid operation despite common type!"); 69154569448SJordy Rose rhs = nonloc::ConcreteInt(*newRHS); 69254569448SJordy Rose lhs = nonloc::SymbolVal(symIntExpr->getLHS()); 69354569448SJordy Rose continue; 694fa0734ecSArgyrios Kyrtzidis } 695fa0734ecSArgyrios Kyrtzidis } 696fa0734ecSArgyrios Kyrtzidis 69754569448SJordy Rose // Otherwise, make a SymIntExpr out of the expression. 69854569448SJordy Rose return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy); 69954569448SJordy Rose } 7003b4c3ea2SJordan Rose } 701fa0734ecSArgyrios Kyrtzidis 70254569448SJordy Rose // Is the RHS a constant? 70354569448SJordy Rose if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) 70454569448SJordy Rose return MakeSymIntVal(Sym, op, *RHSValue, resultTy); 705fa0734ecSArgyrios Kyrtzidis 7062bbccca9SAdam Balogh if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy)) 7072bbccca9SAdam Balogh return *V; 7082bbccca9SAdam Balogh 70954569448SJordy Rose // Give up -- this is not a symbolic expression we can handle. 710bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 711fa0734ecSArgyrios Kyrtzidis } 712fa0734ecSArgyrios Kyrtzidis } 713fa0734ecSArgyrios Kyrtzidis } 714fa0734ecSArgyrios Kyrtzidis } 715fa0734ecSArgyrios Kyrtzidis 716bac964e1SAnna Zaks static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR, 717bac964e1SAnna Zaks const FieldRegion *RightFR, 718bac964e1SAnna Zaks BinaryOperator::Opcode op, 719bac964e1SAnna Zaks QualType resultTy, 720bac964e1SAnna Zaks SimpleSValBuilder &SVB) { 721bac964e1SAnna Zaks // Only comparisons are meaningful here! 722bac964e1SAnna Zaks if (!BinaryOperator::isComparisonOp(op)) 723bac964e1SAnna Zaks return UnknownVal(); 724bac964e1SAnna Zaks 725bac964e1SAnna Zaks // Next, see if the two FRs have the same super-region. 726bac964e1SAnna Zaks // FIXME: This doesn't handle casts yet, and simply stripping the casts 727bac964e1SAnna Zaks // doesn't help. 728bac964e1SAnna Zaks if (LeftFR->getSuperRegion() != RightFR->getSuperRegion()) 729bac964e1SAnna Zaks return UnknownVal(); 730bac964e1SAnna Zaks 731bac964e1SAnna Zaks const FieldDecl *LeftFD = LeftFR->getDecl(); 732bac964e1SAnna Zaks const FieldDecl *RightFD = RightFR->getDecl(); 733bac964e1SAnna Zaks const RecordDecl *RD = LeftFD->getParent(); 734bac964e1SAnna Zaks 735bac964e1SAnna Zaks // Make sure the two FRs are from the same kind of record. Just in case! 736bac964e1SAnna Zaks // FIXME: This is probably where inheritance would be a problem. 737bac964e1SAnna Zaks if (RD != RightFD->getParent()) 738bac964e1SAnna Zaks return UnknownVal(); 739bac964e1SAnna Zaks 740bac964e1SAnna Zaks // We know for sure that the two fields are not the same, since that 741bac964e1SAnna Zaks // would have given us the same SVal. 742bac964e1SAnna Zaks if (op == BO_EQ) 743bac964e1SAnna Zaks return SVB.makeTruthVal(false, resultTy); 744bac964e1SAnna Zaks if (op == BO_NE) 745bac964e1SAnna Zaks return SVB.makeTruthVal(true, resultTy); 746bac964e1SAnna Zaks 747bac964e1SAnna Zaks // Iterate through the fields and see which one comes first. 748bac964e1SAnna Zaks // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field 749bac964e1SAnna Zaks // members and the units in which bit-fields reside have addresses that 750bac964e1SAnna Zaks // increase in the order in which they are declared." 751bac964e1SAnna Zaks bool leftFirst = (op == BO_LT || op == BO_LE); 752e8a8baefSAaron Ballman for (const auto *I : RD->fields()) { 753e8a8baefSAaron Ballman if (I == LeftFD) 754bac964e1SAnna Zaks return SVB.makeTruthVal(leftFirst, resultTy); 755e8a8baefSAaron Ballman if (I == RightFD) 756bac964e1SAnna Zaks return SVB.makeTruthVal(!leftFirst, resultTy); 757bac964e1SAnna Zaks } 758bac964e1SAnna Zaks 759bac964e1SAnna Zaks llvm_unreachable("Fields not found in parent record's definition"); 760bac964e1SAnna Zaks } 761bac964e1SAnna Zaks 7624d5b824eSVince Bridgers // This is used in debug builds only for now because some downstream users 7634d5b824eSVince Bridgers // may hit this assert in their subsequent merges. 7644d5b824eSVince Bridgers // There are still places in the analyzer where equal bitwidth Locs 7654d5b824eSVince Bridgers // are compared, and need to be found and corrected. Recent previous fixes have 7664d5b824eSVince Bridgers // addressed the known problems of making NULLs with specific bitwidths 7674d5b824eSVince Bridgers // for Loc comparisons along with deprecation of APIs for the same purpose. 7684d5b824eSVince Bridgers // 7694d5b824eSVince Bridgers static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc, 7704d5b824eSVince Bridgers Loc LhsLoc) { 7714d5b824eSVince Bridgers // Implements a "best effort" check for RhsLoc and LhsLoc bit widths 7724d5b824eSVince Bridgers ASTContext &Ctx = State->getStateManager().getContext(); 7734d5b824eSVince Bridgers uint64_t RhsBitwidth = 7744d5b824eSVince Bridgers RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx)); 7754d5b824eSVince Bridgers uint64_t LhsBitwidth = 7764d5b824eSVince Bridgers LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx)); 7774d5b824eSVince Bridgers if (RhsBitwidth && LhsBitwidth && 7784d5b824eSVince Bridgers (LhsLoc.getSubKind() == RhsLoc.getSubKind())) { 7794d5b824eSVince Bridgers assert(RhsBitwidth == LhsBitwidth && 7804d5b824eSVince Bridgers "RhsLoc and LhsLoc bitwidth must be same!"); 7814d5b824eSVince Bridgers } 7824d5b824eSVince Bridgers } 7834d5b824eSVince Bridgers 784fa0734ecSArgyrios Kyrtzidis // FIXME: all this logic will change if/when we have MemRegion::getLocation(). 78549b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, 786fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 787fa0734ecSArgyrios Kyrtzidis Loc lhs, Loc rhs, 788fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 7894d5b824eSVince Bridgers 7904d5b824eSVince Bridgers // Assert that bitwidth of lhs and rhs are the same. 7914d5b824eSVince Bridgers // This can happen if two different address spaces are used, 7924d5b824eSVince Bridgers // and the bitwidths of the address spaces are different. 7934d5b824eSVince Bridgers // See LIT case clang/test/Analysis/cstring-checker-addressspace.c 7944d5b824eSVince Bridgers // FIXME: See comment above in the function assertEqualBitWidths 7954d5b824eSVince Bridgers assertEqualBitWidths(state, rhs, lhs); 7964d5b824eSVince Bridgers 797fa0734ecSArgyrios Kyrtzidis // Only comparisons and subtractions are valid operations on two pointers. 798fa0734ecSArgyrios Kyrtzidis // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15]. 799fa0734ecSArgyrios Kyrtzidis // However, if a pointer is casted to an integer, evalBinOpNN may end up 800fa0734ecSArgyrios Kyrtzidis // calling this function with another operation (PR7527). We don't attempt to 801fa0734ecSArgyrios Kyrtzidis // model this for now, but it could be useful, particularly when the 802fa0734ecSArgyrios Kyrtzidis // "location" is actually an integer value that's been passed through a void*. 803fa0734ecSArgyrios Kyrtzidis if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub)) 804fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 805fa0734ecSArgyrios Kyrtzidis 806fa0734ecSArgyrios Kyrtzidis // Special cases for when both sides are identical. 807fa0734ecSArgyrios Kyrtzidis if (lhs == rhs) { 808fa0734ecSArgyrios Kyrtzidis switch (op) { 809fa0734ecSArgyrios Kyrtzidis default: 81083d382b1SDavid Blaikie llvm_unreachable("Unimplemented operation for two identical values"); 811fa0734ecSArgyrios Kyrtzidis case BO_Sub: 812fa0734ecSArgyrios Kyrtzidis return makeZeroVal(resultTy); 813fa0734ecSArgyrios Kyrtzidis case BO_EQ: 814fa0734ecSArgyrios Kyrtzidis case BO_LE: 815fa0734ecSArgyrios Kyrtzidis case BO_GE: 816fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 817fa0734ecSArgyrios Kyrtzidis case BO_NE: 818fa0734ecSArgyrios Kyrtzidis case BO_LT: 819fa0734ecSArgyrios Kyrtzidis case BO_GT: 820fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 821fa0734ecSArgyrios Kyrtzidis } 822fa0734ecSArgyrios Kyrtzidis } 823fa0734ecSArgyrios Kyrtzidis 824fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) { 825fa0734ecSArgyrios Kyrtzidis default: 82683d382b1SDavid Blaikie llvm_unreachable("Ordering not implemented for this Loc."); 827fa0734ecSArgyrios Kyrtzidis 828fa0734ecSArgyrios Kyrtzidis case loc::GotoLabelKind: 829fa0734ecSArgyrios Kyrtzidis // The only thing we know about labels is that they're non-null. 830fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant()) { 831fa0734ecSArgyrios Kyrtzidis switch (op) { 832fa0734ecSArgyrios Kyrtzidis default: 833fa0734ecSArgyrios Kyrtzidis break; 834fa0734ecSArgyrios Kyrtzidis case BO_Sub: 83501ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 836fa0734ecSArgyrios Kyrtzidis case BO_EQ: 837fa0734ecSArgyrios Kyrtzidis case BO_LE: 838fa0734ecSArgyrios Kyrtzidis case BO_LT: 839fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 840fa0734ecSArgyrios Kyrtzidis case BO_NE: 841fa0734ecSArgyrios Kyrtzidis case BO_GT: 842fa0734ecSArgyrios Kyrtzidis case BO_GE: 843fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 844fa0734ecSArgyrios Kyrtzidis } 845fa0734ecSArgyrios Kyrtzidis } 846fa0734ecSArgyrios Kyrtzidis // There may be two labels for the same location, and a function region may 847fa0734ecSArgyrios Kyrtzidis // have the same address as a label at the start of the function (depending 848fa0734ecSArgyrios Kyrtzidis // on the ABI). 849fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably do a comparison against other MemRegions, though. 850fa0734ecSArgyrios Kyrtzidis // FIXME: is there a way to tell if two labels refer to the same location? 851fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 852fa0734ecSArgyrios Kyrtzidis 853fa0734ecSArgyrios Kyrtzidis case loc::ConcreteIntKind: { 854*f6eab437SBalazs Benics auto L = lhs.castAs<loc::ConcreteInt>(); 855*f6eab437SBalazs Benics 856fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant, 857fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager. 858fa0734ecSArgyrios Kyrtzidis if (SymbolRef rSym = rhs.getAsLocSymbol()) { 859c0402c69SDominic Chen // We can only build expressions with symbols on the left, 860c0402c69SDominic Chen // so we need a reversible operator. 861c70f1d63SRichard Smith if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp) 862c0402c69SDominic Chen return UnknownVal(); 86335610d21SDominic Chen 864604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op); 865*f6eab437SBalazs Benics return makeNonLoc(rSym, op, L.getValue(), resultTy); 866fa0734ecSArgyrios Kyrtzidis } 867fa0734ecSArgyrios Kyrtzidis 868fa0734ecSArgyrios Kyrtzidis // If both operands are constants, just perform the operation. 86905785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { 870*f6eab437SBalazs Benics assert(BinaryOperator::isComparisonOp(op) || op == BO_Sub); 8718eca04b2SJordan Rose 872*f6eab437SBalazs Benics if (const auto *ResultInt = 873*f6eab437SBalazs Benics BasicVals.evalAPSInt(op, L.getValue(), rInt->getValue())) 874*f6eab437SBalazs Benics return evalCast(nonloc::ConcreteInt(*ResultInt), resultTy, QualType{}); 875fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 876fa0734ecSArgyrios Kyrtzidis } 877fa0734ecSArgyrios Kyrtzidis 878fa0734ecSArgyrios Kyrtzidis // Special case comparisons against NULL. 879fa0734ecSArgyrios Kyrtzidis // This must come after the test if the RHS is a symbol, which is used to 880fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed 881fa0734ecSArgyrios Kyrtzidis // to be non-NULL, as is any label. 8822fdacbc5SDavid Blaikie assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>()); 883fa0734ecSArgyrios Kyrtzidis if (lhs.isZeroConstant()) { 884fa0734ecSArgyrios Kyrtzidis switch (op) { 885fa0734ecSArgyrios Kyrtzidis default: 886fa0734ecSArgyrios Kyrtzidis break; 887fa0734ecSArgyrios Kyrtzidis case BO_EQ: 888fa0734ecSArgyrios Kyrtzidis case BO_GT: 889fa0734ecSArgyrios Kyrtzidis case BO_GE: 890fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 891fa0734ecSArgyrios Kyrtzidis case BO_NE: 892fa0734ecSArgyrios Kyrtzidis case BO_LT: 893fa0734ecSArgyrios Kyrtzidis case BO_LE: 894fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 895fa0734ecSArgyrios Kyrtzidis } 896fa0734ecSArgyrios Kyrtzidis } 897fa0734ecSArgyrios Kyrtzidis 898fa0734ecSArgyrios Kyrtzidis // Comparing an arbitrary integer to a region or label address is 899fa0734ecSArgyrios Kyrtzidis // completely unknowable. 900fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 901fa0734ecSArgyrios Kyrtzidis } 90273f018e3SArtem Dergachev case loc::MemRegionValKind: { 90305785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { 904fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant, 905fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager. 906f4963ff1SAlexander Shaposhnikov if (SymbolRef lSym = lhs.getAsLocSymbol(true)) { 907f4963ff1SAlexander Shaposhnikov if (BinaryOperator::isComparisonOp(op)) 908fa0734ecSArgyrios Kyrtzidis return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy); 909f4963ff1SAlexander Shaposhnikov return UnknownVal(); 910f4963ff1SAlexander Shaposhnikov } 911fa0734ecSArgyrios Kyrtzidis // Special case comparisons to NULL. 912fa0734ecSArgyrios Kyrtzidis // This must come after the test if the LHS is a symbol, which is used to 913fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed 914fa0734ecSArgyrios Kyrtzidis // to be non-NULL. 915fa0734ecSArgyrios Kyrtzidis if (rInt->isZeroConstant()) { 916acd080b9SJordan Rose if (op == BO_Sub) 91701ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 918acd080b9SJordan Rose 919acd080b9SJordan Rose if (BinaryOperator::isComparisonOp(op)) { 920acd080b9SJordan Rose QualType boolType = getContext().BoolTy; 92101ddfa95SDenys Petrov NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>(); 922acd080b9SJordan Rose NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>(); 923acd080b9SJordan Rose return evalBinOpNN(state, op, l, r, resultTy); 924fa0734ecSArgyrios Kyrtzidis } 925fa0734ecSArgyrios Kyrtzidis } 926fa0734ecSArgyrios Kyrtzidis 927fa0734ecSArgyrios Kyrtzidis // Comparing a region to an arbitrary integer is completely unknowable. 928fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 929fa0734ecSArgyrios Kyrtzidis } 930fa0734ecSArgyrios Kyrtzidis 931fa0734ecSArgyrios Kyrtzidis // Get both values as regions, if possible. 932fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftMR = lhs.getAsRegion(); 93373f018e3SArtem Dergachev assert(LeftMR && "MemRegionValKind SVal doesn't have a region!"); 934fa0734ecSArgyrios Kyrtzidis 935fa0734ecSArgyrios Kyrtzidis const MemRegion *RightMR = rhs.getAsRegion(); 936fa0734ecSArgyrios Kyrtzidis if (!RightMR) 937fa0734ecSArgyrios Kyrtzidis // The RHS is probably a label, which in theory could address a region. 938fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably make a more useful statement about non-code 939fa0734ecSArgyrios Kyrtzidis // regions, though. 940fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 941fa0734ecSArgyrios Kyrtzidis 942fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftBase = LeftMR->getBaseRegion(); 943fa0734ecSArgyrios Kyrtzidis const MemRegion *RightBase = RightMR->getBaseRegion(); 9443b4c3ea2SJordan Rose const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace(); 9453b4c3ea2SJordan Rose const MemSpaceRegion *RightMS = RightBase->getMemorySpace(); 9463b4c3ea2SJordan Rose const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion(); 9473563fde6SAnna Zaks 9483563fde6SAnna Zaks // If the two regions are from different known memory spaces they cannot be 9493563fde6SAnna Zaks // equal. Also, assume that no symbolic region (whose memory space is 9503563fde6SAnna Zaks // unknown) is on the stack. 9513563fde6SAnna Zaks if (LeftMS != RightMS && 9523563fde6SAnna Zaks ((LeftMS != UnknownMS && RightMS != UnknownMS) || 9533563fde6SAnna Zaks (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) { 954fa0734ecSArgyrios Kyrtzidis switch (op) { 955fa0734ecSArgyrios Kyrtzidis default: 956fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 957fa0734ecSArgyrios Kyrtzidis case BO_EQ: 958fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 959fa0734ecSArgyrios Kyrtzidis case BO_NE: 960fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 961fa0734ecSArgyrios Kyrtzidis } 962fa0734ecSArgyrios Kyrtzidis } 963fa0734ecSArgyrios Kyrtzidis 9643563fde6SAnna Zaks // If both values wrap regions, see if they're from different base regions. 9653563fde6SAnna Zaks // Note, heap base symbolic regions are assumed to not alias with 9663563fde6SAnna Zaks // each other; for example, we assume that malloc returns different address 9673563fde6SAnna Zaks // on each invocation. 968aacc03c9SArtem Dergachev // FIXME: ObjC object pointers always reside on the heap, but currently 969aacc03c9SArtem Dergachev // we treat their memory space as unknown, because symbolic pointers 970aacc03c9SArtem Dergachev // to ObjC objects may alias. There should be a way to construct 971aacc03c9SArtem Dergachev // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker 972aacc03c9SArtem Dergachev // guesses memory space for ObjC object pointers manually instead of 973aacc03c9SArtem Dergachev // relying on us. 9743563fde6SAnna Zaks if (LeftBase != RightBase && 9753563fde6SAnna Zaks ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) || 976a7dcc996SAnna Zaks (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){ 9779d96f843STed Kremenek switch (op) { 9789d96f843STed Kremenek default: 9793563fde6SAnna Zaks return UnknownVal(); 9809d96f843STed Kremenek case BO_EQ: 9819d96f843STed Kremenek return makeTruthVal(false, resultTy); 9829d96f843STed Kremenek case BO_NE: 9839d96f843STed Kremenek return makeTruthVal(true, resultTy); 9849d96f843STed Kremenek } 9859d96f843STed Kremenek } 986fa0734ecSArgyrios Kyrtzidis 987bac964e1SAnna Zaks // Handle special cases for when both regions are element regions. 988fa0734ecSArgyrios Kyrtzidis const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR); 989bac964e1SAnna Zaks const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR); 990bac964e1SAnna Zaks if (RightER && LeftER) { 991fa0734ecSArgyrios Kyrtzidis // Next, see if the two ERs have the same super-region and matching types. 992fa0734ecSArgyrios Kyrtzidis // FIXME: This should do something useful even if the types don't match, 993fa0734ecSArgyrios Kyrtzidis // though if both indexes are constant the RegionRawOffset path will 994fa0734ecSArgyrios Kyrtzidis // give the correct answer. 995fa0734ecSArgyrios Kyrtzidis if (LeftER->getSuperRegion() == RightER->getSuperRegion() && 996fa0734ecSArgyrios Kyrtzidis LeftER->getElementType() == RightER->getElementType()) { 997fa0734ecSArgyrios Kyrtzidis // Get the left index and cast it to the correct type. 998fa0734ecSArgyrios Kyrtzidis // If the index is unknown or undefined, bail out here. 999fa0734ecSArgyrios Kyrtzidis SVal LeftIndexVal = LeftER->getIndex(); 100005785d16SDavid Blaikie Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>(); 1001fa0734ecSArgyrios Kyrtzidis if (!LeftIndex) 1002fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 100301ddfa95SDenys Petrov LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{}); 10042fdacbc5SDavid Blaikie LeftIndex = LeftIndexVal.getAs<NonLoc>(); 1005fa0734ecSArgyrios Kyrtzidis if (!LeftIndex) 1006fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1007fa0734ecSArgyrios Kyrtzidis 1008fa0734ecSArgyrios Kyrtzidis // Do the same for the right index. 1009fa0734ecSArgyrios Kyrtzidis SVal RightIndexVal = RightER->getIndex(); 101005785d16SDavid Blaikie Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>(); 1011fa0734ecSArgyrios Kyrtzidis if (!RightIndex) 1012fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 101301ddfa95SDenys Petrov RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{}); 10142fdacbc5SDavid Blaikie RightIndex = RightIndexVal.getAs<NonLoc>(); 1015fa0734ecSArgyrios Kyrtzidis if (!RightIndex) 1016fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1017fa0734ecSArgyrios Kyrtzidis 1018fa0734ecSArgyrios Kyrtzidis // Actually perform the operation. 1019fa0734ecSArgyrios Kyrtzidis // evalBinOpNN expects the two indexes to already be the right type. 1020fa0734ecSArgyrios Kyrtzidis return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy); 1021fa0734ecSArgyrios Kyrtzidis } 1022bac964e1SAnna Zaks } 1023fa0734ecSArgyrios Kyrtzidis 1024bac964e1SAnna Zaks // Special handling of the FieldRegions, even with symbolic offsets. 1025bac964e1SAnna Zaks const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR); 1026bac964e1SAnna Zaks const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR); 1027bac964e1SAnna Zaks if (RightFR && LeftFR) { 1028bac964e1SAnna Zaks SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy, 1029bac964e1SAnna Zaks *this); 1030bac964e1SAnna Zaks if (!R.isUnknown()) 1031bac964e1SAnna Zaks return R; 1032bac964e1SAnna Zaks } 1033bac964e1SAnna Zaks 1034bac964e1SAnna Zaks // Compare the regions using the raw offsets. 1035bac964e1SAnna Zaks RegionOffset LeftOffset = LeftMR->getAsOffset(); 1036bac964e1SAnna Zaks RegionOffset RightOffset = RightMR->getAsOffset(); 1037fa0734ecSArgyrios Kyrtzidis 10380dbb783cSCraig Topper if (LeftOffset.getRegion() != nullptr && 1039bac964e1SAnna Zaks LeftOffset.getRegion() == RightOffset.getRegion() && 1040bac964e1SAnna Zaks !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) { 1041bac964e1SAnna Zaks int64_t left = LeftOffset.getOffset(); 1042bac964e1SAnna Zaks int64_t right = RightOffset.getOffset(); 1043fa0734ecSArgyrios Kyrtzidis 1044fa0734ecSArgyrios Kyrtzidis switch (op) { 1045fa0734ecSArgyrios Kyrtzidis default: 1046fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1047fa0734ecSArgyrios Kyrtzidis case BO_LT: 1048fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left < right, resultTy); 1049fa0734ecSArgyrios Kyrtzidis case BO_GT: 1050fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left > right, resultTy); 1051fa0734ecSArgyrios Kyrtzidis case BO_LE: 1052fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left <= right, resultTy); 1053fa0734ecSArgyrios Kyrtzidis case BO_GE: 1054fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left >= right, resultTy); 1055fa0734ecSArgyrios Kyrtzidis case BO_EQ: 1056fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left == right, resultTy); 1057fa0734ecSArgyrios Kyrtzidis case BO_NE: 1058fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left != right, resultTy); 1059fa0734ecSArgyrios Kyrtzidis } 1060fa0734ecSArgyrios Kyrtzidis } 1061fa0734ecSArgyrios Kyrtzidis 10623b4c3ea2SJordan Rose // At this point we're not going to get a good answer, but we can try 10633b4c3ea2SJordan Rose // conjuring an expression instead. 10643b4c3ea2SJordan Rose SymbolRef LHSSym = lhs.getAsLocSymbol(); 10653b4c3ea2SJordan Rose SymbolRef RHSSym = rhs.getAsLocSymbol(); 10663b4c3ea2SJordan Rose if (LHSSym && RHSSym) 10673b4c3ea2SJordan Rose return makeNonLoc(LHSSym, op, RHSSym, resultTy); 10683b4c3ea2SJordan Rose 1069fa0734ecSArgyrios Kyrtzidis // If we get here, we have no way of comparing the regions. 1070fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1071fa0734ecSArgyrios Kyrtzidis } 1072fa0734ecSArgyrios Kyrtzidis } 1073fa0734ecSArgyrios Kyrtzidis } 1074fa0734ecSArgyrios Kyrtzidis 107549b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state, 10769cbfdde2SValeriy Savchenko BinaryOperator::Opcode op, Loc lhs, 10779cbfdde2SValeriy Savchenko NonLoc rhs, QualType resultTy) { 107864c01f7bSDevin Coughlin if (op >= BO_PtrMemD && op <= BO_PtrMemI) { 107964c01f7bSDevin Coughlin if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) { 108064c01f7bSDevin Coughlin if (PTMSV->isNullMemberPointer()) 108164c01f7bSDevin Coughlin return UndefinedVal(); 10829cbfdde2SValeriy Savchenko 10839cbfdde2SValeriy Savchenko auto getFieldLValue = [&](const auto *FD) -> SVal { 108464c01f7bSDevin Coughlin SVal Result = lhs; 108564c01f7bSDevin Coughlin 108664c01f7bSDevin Coughlin for (const auto &I : *PTMSV) 108764c01f7bSDevin Coughlin Result = StateMgr.getStoreManager().evalDerivedToBase( 108864c01f7bSDevin Coughlin Result, I->getType(), I->isVirtual()); 10899cbfdde2SValeriy Savchenko 109064c01f7bSDevin Coughlin return state->getLValue(FD, Result); 10919cbfdde2SValeriy Savchenko }; 10929cbfdde2SValeriy Savchenko 10939cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) { 10949cbfdde2SValeriy Savchenko return getFieldLValue(FD); 10959cbfdde2SValeriy Savchenko } 10969cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) { 10979cbfdde2SValeriy Savchenko return getFieldLValue(FD); 109864c01f7bSDevin Coughlin } 109964c01f7bSDevin Coughlin } 110064c01f7bSDevin Coughlin 110164c01f7bSDevin Coughlin return rhs; 110264c01f7bSDevin Coughlin } 110364c01f7bSDevin Coughlin 1104686df322SJordan Rose assert(!BinaryOperator::isComparisonOp(op) && 1105686df322SJordan Rose "arguments to comparison ops must be of the same type"); 1106fa0734ecSArgyrios Kyrtzidis 1107fa0734ecSArgyrios Kyrtzidis // Special case: rhs is a zero constant. 1108fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant()) 1109fa0734ecSArgyrios Kyrtzidis return lhs; 1110fa0734ecSArgyrios Kyrtzidis 111121524676SGabor Horvath // Perserve the null pointer so that it can be found by the DerefChecker. 111221524676SGabor Horvath if (lhs.isZeroConstant()) 111321524676SGabor Horvath return lhs; 111421524676SGabor Horvath 1115fa0734ecSArgyrios Kyrtzidis // We are dealing with pointer arithmetic. 1116fa0734ecSArgyrios Kyrtzidis 1117fa0734ecSArgyrios Kyrtzidis // Handle pointer arithmetic on constant values. 111805785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) { 111905785d16SDavid Blaikie if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) { 1120fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &leftI = lhsInt->getValue(); 1121fa0734ecSArgyrios Kyrtzidis assert(leftI.isUnsigned()); 1122fa0734ecSArgyrios Kyrtzidis llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true); 1123fa0734ecSArgyrios Kyrtzidis 1124fa0734ecSArgyrios Kyrtzidis // Convert the bitwidth of rightI. This should deal with overflow 1125fa0734ecSArgyrios Kyrtzidis // since we are dealing with concrete values. 1126fa0734ecSArgyrios Kyrtzidis rightI = rightI.extOrTrunc(leftI.getBitWidth()); 1127fa0734ecSArgyrios Kyrtzidis 1128fa0734ecSArgyrios Kyrtzidis // Offset the increment by the pointer size. 1129fa0734ecSArgyrios Kyrtzidis llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true); 113021524676SGabor Horvath QualType pointeeType = resultTy->getPointeeType(); 113121524676SGabor Horvath Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity(); 1132fa0734ecSArgyrios Kyrtzidis rightI *= Multiplicand; 1133fa0734ecSArgyrios Kyrtzidis 1134fa0734ecSArgyrios Kyrtzidis // Compute the adjusted pointer. 1135fa0734ecSArgyrios Kyrtzidis switch (op) { 1136fa0734ecSArgyrios Kyrtzidis case BO_Add: 1137fa0734ecSArgyrios Kyrtzidis rightI = leftI + rightI; 1138fa0734ecSArgyrios Kyrtzidis break; 1139fa0734ecSArgyrios Kyrtzidis case BO_Sub: 1140fa0734ecSArgyrios Kyrtzidis rightI = leftI - rightI; 1141fa0734ecSArgyrios Kyrtzidis break; 1142fa0734ecSArgyrios Kyrtzidis default: 1143fa0734ecSArgyrios Kyrtzidis llvm_unreachable("Invalid pointer arithmetic operation"); 1144fa0734ecSArgyrios Kyrtzidis } 1145fa0734ecSArgyrios Kyrtzidis return loc::ConcreteInt(getBasicValueFactory().getValue(rightI)); 1146fa0734ecSArgyrios Kyrtzidis } 1147fa0734ecSArgyrios Kyrtzidis } 1148fa0734ecSArgyrios Kyrtzidis 1149fa0734ecSArgyrios Kyrtzidis // Handle cases where 'lhs' is a region. 1150fa0734ecSArgyrios Kyrtzidis if (const MemRegion *region = lhs.getAsRegion()) { 11512fdacbc5SDavid Blaikie rhs = convertToArrayIndex(rhs).castAs<NonLoc>(); 1152fa0734ecSArgyrios Kyrtzidis SVal index = UnknownVal(); 11536dd11048SArtem Dergachev const SubRegion *superR = nullptr; 11547333a9eaSArtem Dergachev // We need to know the type of the pointer in order to add an integer to it. 11557333a9eaSArtem Dergachev // Depending on the type, different amount of bytes is added. 1156fa0734ecSArgyrios Kyrtzidis QualType elementType; 1157fa0734ecSArgyrios Kyrtzidis 1158fa0734ecSArgyrios Kyrtzidis if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) { 115957a4a152STed Kremenek assert(op == BO_Add || op == BO_Sub); 116057a4a152STed Kremenek index = evalBinOpNN(state, op, elemReg->getIndex(), rhs, 1161fa0734ecSArgyrios Kyrtzidis getArrayIndexType()); 11626dd11048SArtem Dergachev superR = cast<SubRegion>(elemReg->getSuperRegion()); 1163fa0734ecSArgyrios Kyrtzidis elementType = elemReg->getElementType(); 1164fa0734ecSArgyrios Kyrtzidis } 1165fa0734ecSArgyrios Kyrtzidis else if (isa<SubRegion>(region)) { 1166c4b28a8fSGabor Horvath assert(op == BO_Add || op == BO_Sub); 1167c4b28a8fSGabor Horvath index = (op == BO_Add) ? rhs : evalMinus(rhs); 11686dd11048SArtem Dergachev superR = cast<SubRegion>(region); 11697333a9eaSArtem Dergachev // TODO: Is this actually reliable? Maybe improving our MemRegion 11707333a9eaSArtem Dergachev // hierarchy to provide typed regions for all non-void pointers would be 11717333a9eaSArtem Dergachev // better. For instance, we cannot extend this towards LocAsInteger 11727333a9eaSArtem Dergachev // operations, where result type of the expression is integer. 1173d1a08b6eSJordan Rose if (resultTy->isAnyPointerType()) 1174d1a08b6eSJordan Rose elementType = resultTy->getPointeeType(); 1175fa0734ecSArgyrios Kyrtzidis } 1176fa0734ecSArgyrios Kyrtzidis 1177df1bb8a6SArtem Dergachev // Represent arithmetic on void pointers as arithmetic on char pointers. 1178df1bb8a6SArtem Dergachev // It is fine when a TypedValueRegion of char value type represents 1179df1bb8a6SArtem Dergachev // a void pointer. Note that arithmetic on void pointers is a GCC extension. 1180df1bb8a6SArtem Dergachev if (elementType->isVoidType()) 1181df1bb8a6SArtem Dergachev elementType = getContext().CharTy; 1182df1bb8a6SArtem Dergachev 118305785d16SDavid Blaikie if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) { 1184fa0734ecSArgyrios Kyrtzidis return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV, 1185fa0734ecSArgyrios Kyrtzidis superR, getContext())); 1186fa0734ecSArgyrios Kyrtzidis } 1187fa0734ecSArgyrios Kyrtzidis } 1188fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1189fa0734ecSArgyrios Kyrtzidis } 1190fa0734ecSArgyrios Kyrtzidis 119149b1e38eSTed Kremenek const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state, 1192fa0734ecSArgyrios Kyrtzidis SVal V) { 11939ff67a9dSGeorge Karpenkov V = simplifySVal(state, V); 1194fa0734ecSArgyrios Kyrtzidis if (V.isUnknownOrUndef()) 11950dbb783cSCraig Topper return nullptr; 1196fa0734ecSArgyrios Kyrtzidis 119705785d16SDavid Blaikie if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>()) 1198fa0734ecSArgyrios Kyrtzidis return &X->getValue(); 1199fa0734ecSArgyrios Kyrtzidis 120005785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>()) 1201fa0734ecSArgyrios Kyrtzidis return &X->getValue(); 1202fa0734ecSArgyrios Kyrtzidis 1203fa0734ecSArgyrios Kyrtzidis if (SymbolRef Sym = V.getAsSymbol()) 1204244e1d7dSTed Kremenek return state->getConstraintManager().getSymVal(state, Sym); 1205fa0734ecSArgyrios Kyrtzidis 12060dbb783cSCraig Topper return nullptr; 1207fa0734ecSArgyrios Kyrtzidis } 120812294f8dSArtem Dergachev 1209978431e8SGabor Marton SVal SimpleSValBuilder::simplifyUntilFixpoint(ProgramStateRef State, SVal Val) { 1210978431e8SGabor Marton SVal SimplifiedVal = simplifySValOnce(State, Val); 1211978431e8SGabor Marton while (SimplifiedVal != Val) { 1212978431e8SGabor Marton Val = SimplifiedVal; 1213978431e8SGabor Marton SimplifiedVal = simplifySValOnce(State, Val); 1214978431e8SGabor Marton } 1215978431e8SGabor Marton return SimplifiedVal; 1216978431e8SGabor Marton } 1217978431e8SGabor Marton 121812294f8dSArtem Dergachev SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { 1219978431e8SGabor Marton return simplifyUntilFixpoint(State, V); 1220978431e8SGabor Marton } 1221978431e8SGabor Marton 1222978431e8SGabor Marton SVal SimpleSValBuilder::simplifySValOnce(ProgramStateRef State, SVal V) { 122312294f8dSArtem Dergachev // For now, this function tries to constant-fold symbols inside a 122412294f8dSArtem Dergachev // nonloc::SymbolVal, and does nothing else. More simplifications should 122512294f8dSArtem Dergachev // be possible, such as constant-folding an index in an ElementRegion. 122612294f8dSArtem Dergachev 122712294f8dSArtem Dergachev class Simplifier : public FullSValVisitor<Simplifier, SVal> { 122812294f8dSArtem Dergachev ProgramStateRef State; 122912294f8dSArtem Dergachev SValBuilder &SVB; 123012294f8dSArtem Dergachev 123122746d7dSArtem Dergachev // Cache results for the lifetime of the Simplifier. Results change every 123222746d7dSArtem Dergachev // time new constraints are added to the program state, which is the whole 123322746d7dSArtem Dergachev // point of simplifying, and for that very reason it's pointless to maintain 123422746d7dSArtem Dergachev // the same cache for the duration of the whole analysis. 123522746d7dSArtem Dergachev llvm::DenseMap<SymbolRef, SVal> Cached; 123622746d7dSArtem Dergachev 123716a1f64cSArtem Dergachev static bool isUnchanged(SymbolRef Sym, SVal Val) { 123816a1f64cSArtem Dergachev return Sym == Val.getAsSymbol(); 123916a1f64cSArtem Dergachev } 124016a1f64cSArtem Dergachev 12419fe9a95fSArtem Dergachev SVal cache(SymbolRef Sym, SVal V) { 12429fe9a95fSArtem Dergachev Cached[Sym] = V; 12439fe9a95fSArtem Dergachev return V; 12449fe9a95fSArtem Dergachev } 12459fe9a95fSArtem Dergachev 12469fe9a95fSArtem Dergachev SVal skip(SymbolRef Sym) { 12479fe9a95fSArtem Dergachev return cache(Sym, SVB.makeSymbolVal(Sym)); 12489fe9a95fSArtem Dergachev } 12499fe9a95fSArtem Dergachev 12500a17896fSGabor Marton // Return the known const value for the Sym if available, or return Undef 12510a17896fSGabor Marton // otherwise. 12520a17896fSGabor Marton SVal getConst(SymbolRef Sym) { 12530a17896fSGabor Marton const llvm::APSInt *Const = 12540a17896fSGabor Marton State->getConstraintManager().getSymVal(State, Sym); 12550a17896fSGabor Marton if (Const) 12560a17896fSGabor Marton return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const) 12570a17896fSGabor Marton : (SVal)SVB.makeIntVal(*Const); 12580a17896fSGabor Marton return UndefinedVal(); 12590a17896fSGabor Marton } 12600a17896fSGabor Marton 12610a17896fSGabor Marton SVal getConstOrVisit(SymbolRef Sym) { 12620a17896fSGabor Marton const SVal Ret = getConst(Sym); 12630a17896fSGabor Marton if (Ret.isUndef()) 12640a17896fSGabor Marton return Visit(Sym); 12650a17896fSGabor Marton return Ret; 12660a17896fSGabor Marton } 12670a17896fSGabor Marton 126812294f8dSArtem Dergachev public: 126912294f8dSArtem Dergachev Simplifier(ProgramStateRef State) 127012294f8dSArtem Dergachev : State(State), SVB(State->getStateManager().getSValBuilder()) {} 127112294f8dSArtem Dergachev 127212294f8dSArtem Dergachev SVal VisitSymbolData(const SymbolData *S) { 12739fe9a95fSArtem Dergachev // No cache here. 127412294f8dSArtem Dergachev if (const llvm::APSInt *I = 1275d1163790SArtem Dergachev SVB.getKnownValue(State, SVB.makeSymbolVal(S))) 127612294f8dSArtem Dergachev return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I) 127712294f8dSArtem Dergachev : (SVal)SVB.makeIntVal(*I); 127816a1f64cSArtem Dergachev return SVB.makeSymbolVal(S); 127912294f8dSArtem Dergachev } 128012294f8dSArtem Dergachev 12810a17896fSGabor Marton // TODO: Support SymbolCast. 128212294f8dSArtem Dergachev 128312294f8dSArtem Dergachev SVal VisitSymIntExpr(const SymIntExpr *S) { 128422746d7dSArtem Dergachev auto I = Cached.find(S); 128522746d7dSArtem Dergachev if (I != Cached.end()) 128622746d7dSArtem Dergachev return I->second; 128722746d7dSArtem Dergachev 12880a17896fSGabor Marton SVal LHS = getConstOrVisit(S->getLHS()); 12899fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS)) 12909fe9a95fSArtem Dergachev return skip(S); 12919fe9a95fSArtem Dergachev 129212294f8dSArtem Dergachev SVal RHS; 129312294f8dSArtem Dergachev // By looking at the APSInt in the right-hand side of S, we cannot 129412294f8dSArtem Dergachev // figure out if it should be treated as a Loc or as a NonLoc. 129512294f8dSArtem Dergachev // So make our guess by recalling that we cannot multiply pointers 129612294f8dSArtem Dergachev // or compare a pointer to an integer. 129712294f8dSArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) && 129812294f8dSArtem Dergachev BinaryOperator::isComparisonOp(S->getOpcode())) { 129912294f8dSArtem Dergachev // The usual conversion of $sym to &SymRegion{$sym}, as they have 130012294f8dSArtem Dergachev // the same meaning for Loc-type symbols, but the latter form 130112294f8dSArtem Dergachev // is preferred in SVal computations for being Loc itself. 130212294f8dSArtem Dergachev if (SymbolRef Sym = LHS.getAsSymbol()) { 130312294f8dSArtem Dergachev assert(Loc::isLocType(Sym->getType())); 130412294f8dSArtem Dergachev LHS = SVB.makeLoc(Sym); 130512294f8dSArtem Dergachev } 130612294f8dSArtem Dergachev RHS = SVB.makeIntLocVal(S->getRHS()); 130712294f8dSArtem Dergachev } else { 130812294f8dSArtem Dergachev RHS = SVB.makeIntVal(S->getRHS()); 130912294f8dSArtem Dergachev } 131022746d7dSArtem Dergachev 13119fe9a95fSArtem Dergachev return cache( 13129fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 131312294f8dSArtem Dergachev } 131412294f8dSArtem Dergachev 1315ffc32efdSGabor Marton SVal VisitIntSymExpr(const IntSymExpr *S) { 1316ffc32efdSGabor Marton auto I = Cached.find(S); 1317ffc32efdSGabor Marton if (I != Cached.end()) 1318ffc32efdSGabor Marton return I->second; 1319ffc32efdSGabor Marton 13200a17896fSGabor Marton SVal RHS = getConstOrVisit(S->getRHS()); 1321ffc32efdSGabor Marton if (isUnchanged(S->getRHS(), RHS)) 1322ffc32efdSGabor Marton return skip(S); 13230a17896fSGabor Marton 1324ffc32efdSGabor Marton SVal LHS = SVB.makeIntVal(S->getLHS()); 1325ffc32efdSGabor Marton return cache( 1326ffc32efdSGabor Marton S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 1327ffc32efdSGabor Marton } 1328ffc32efdSGabor Marton 132912294f8dSArtem Dergachev SVal VisitSymSymExpr(const SymSymExpr *S) { 133022746d7dSArtem Dergachev auto I = Cached.find(S); 133122746d7dSArtem Dergachev if (I != Cached.end()) 133222746d7dSArtem Dergachev return I->second; 133322746d7dSArtem Dergachev 133405220a90SArtem Dergachev // For now don't try to simplify mixed Loc/NonLoc expressions 133505220a90SArtem Dergachev // because they often appear from LocAsInteger operations 133605220a90SArtem Dergachev // and we don't know how to combine a LocAsInteger 133705220a90SArtem Dergachev // with a concrete value. 133805220a90SArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) != 13399fe9a95fSArtem Dergachev Loc::isLocType(S->getRHS()->getType())) 13409fe9a95fSArtem Dergachev return skip(S); 134105220a90SArtem Dergachev 13420a17896fSGabor Marton SVal LHS = getConstOrVisit(S->getLHS()); 13430a17896fSGabor Marton SVal RHS = getConstOrVisit(S->getRHS()); 13440a17896fSGabor Marton 13459fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS)) 13469fe9a95fSArtem Dergachev return skip(S); 13479fe9a95fSArtem Dergachev 13489fe9a95fSArtem Dergachev return cache( 13499fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 135012294f8dSArtem Dergachev } 135112294f8dSArtem Dergachev 1352b5b2aec1SGabor Marton // FIXME add VisitSymbolCast 1353b5b2aec1SGabor Marton 1354b5b2aec1SGabor Marton SVal VisitUnarySymExpr(const UnarySymExpr *S) { 1355b5b2aec1SGabor Marton auto I = Cached.find(S); 1356b5b2aec1SGabor Marton if (I != Cached.end()) 1357b5b2aec1SGabor Marton return I->second; 1358b5b2aec1SGabor Marton SVal Op = getConstOrVisit(S->getOperand()); 1359b5b2aec1SGabor Marton if (isUnchanged(S->getOperand(), Op)) 1360b5b2aec1SGabor Marton return skip(S); 1361b5b2aec1SGabor Marton 1362b5b2aec1SGabor Marton return cache( 1363b5b2aec1SGabor Marton S, SVB.evalUnaryOp(State, S->getOpcode(), Op, S->getType())); 1364b5b2aec1SGabor Marton } 1365b5b2aec1SGabor Marton 136612294f8dSArtem Dergachev SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); } 136712294f8dSArtem Dergachev 136812294f8dSArtem Dergachev SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); } 136912294f8dSArtem Dergachev 137012294f8dSArtem Dergachev SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) { 137112294f8dSArtem Dergachev // Simplification is much more costly than computing complexity. 137212294f8dSArtem Dergachev // For high complexity, it may be not worth it. 137312294f8dSArtem Dergachev return Visit(V.getSymbol()); 137412294f8dSArtem Dergachev } 137512294f8dSArtem Dergachev 137612294f8dSArtem Dergachev SVal VisitSVal(SVal V) { return V; } 137712294f8dSArtem Dergachev }; 137812294f8dSArtem Dergachev 137916a1f64cSArtem Dergachev // A crude way of preventing this function from calling itself from evalBinOp. 138016a1f64cSArtem Dergachev static bool isReentering = false; 138116a1f64cSArtem Dergachev if (isReentering) 138216a1f64cSArtem Dergachev return V; 138316a1f64cSArtem Dergachev 138416a1f64cSArtem Dergachev isReentering = true; 138516a1f64cSArtem Dergachev SVal SimplifiedV = Simplifier(State).Visit(V); 138616a1f64cSArtem Dergachev isReentering = false; 138716a1f64cSArtem Dergachev 138816a1f64cSArtem Dergachev return SimplifiedV; 138912294f8dSArtem Dergachev } 1390