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); 93fa0734ecSArgyrios Kyrtzidis default: 94fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 95fa0734ecSArgyrios Kyrtzidis } 96fa0734ecSArgyrios Kyrtzidis } 97fa0734ecSArgyrios Kyrtzidis 98fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalComplement(NonLoc X) { 99fa0734ecSArgyrios Kyrtzidis switch (X.getSubKind()) { 100fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: 1012fdacbc5SDavid Blaikie return X.castAs<nonloc::ConcreteInt>().evalComplement(*this); 102fa0734ecSArgyrios Kyrtzidis default: 103fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 104fa0734ecSArgyrios Kyrtzidis } 105fa0734ecSArgyrios Kyrtzidis } 106fa0734ecSArgyrios Kyrtzidis 107*14742443STomasz Kamiński // Checks if the negation the value and flipping sign preserve 108*14742443STomasz Kamiński // the semantics on the operation in the resultType 109*14742443STomasz Kamiński static bool isNegationValuePreserving(const llvm::APSInt &Value, 110*14742443STomasz Kamiński APSIntType ResultType) { 111*14742443STomasz Kamiński const unsigned ValueBits = Value.getSignificantBits(); 112*14742443STomasz Kamiński if (ValueBits == ResultType.getBitWidth()) { 113*14742443STomasz Kamiński // The value is the lowest negative value that is representable 114*14742443STomasz Kamiński // in signed integer with bitWith of result type. The 115*14742443STomasz Kamiński // negation is representable if resultType is unsigned. 116*14742443STomasz Kamiński return ResultType.isUnsigned(); 117*14742443STomasz Kamiński } 118*14742443STomasz Kamiński 119*14742443STomasz Kamiński // If resultType bitWith is higher that number of bits required 120*14742443STomasz Kamiński // to represent RHS, the sign flip produce same value. 121*14742443STomasz Kamiński return ValueBits < ResultType.getBitWidth(); 122*14742443STomasz Kamiński } 123*14742443STomasz Kamiński 124fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 125fa0734ecSArgyrios Kyrtzidis // Transfer function for binary operators. 126fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 127fa0734ecSArgyrios Kyrtzidis 128fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS, 129fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 130fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &RHS, 131fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 132fa0734ecSArgyrios Kyrtzidis bool isIdempotent = false; 133fa0734ecSArgyrios Kyrtzidis 134fa0734ecSArgyrios Kyrtzidis // Check for a few special cases with known reductions first. 135fa0734ecSArgyrios Kyrtzidis switch (op) { 136fa0734ecSArgyrios Kyrtzidis default: 137fa0734ecSArgyrios Kyrtzidis // We can't reduce this case; just treat it normally. 138fa0734ecSArgyrios Kyrtzidis break; 139fa0734ecSArgyrios Kyrtzidis case BO_Mul: 140fa0734ecSArgyrios Kyrtzidis // a*0 and a*1 141fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 142fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 143fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 144fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 145fa0734ecSArgyrios Kyrtzidis break; 146fa0734ecSArgyrios Kyrtzidis case BO_Div: 147fa0734ecSArgyrios Kyrtzidis // a/0 and a/1 148fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 149fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere. 150fa0734ecSArgyrios Kyrtzidis return UndefinedVal(); 151fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 152fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 153fa0734ecSArgyrios Kyrtzidis break; 154fa0734ecSArgyrios Kyrtzidis case BO_Rem: 155fa0734ecSArgyrios Kyrtzidis // a%0 and a%1 156fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 157fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere. 158fa0734ecSArgyrios Kyrtzidis return UndefinedVal(); 159fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 160fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 161fa0734ecSArgyrios Kyrtzidis break; 162fa0734ecSArgyrios Kyrtzidis case BO_Add: 163fa0734ecSArgyrios Kyrtzidis case BO_Sub: 164fa0734ecSArgyrios Kyrtzidis case BO_Shl: 165fa0734ecSArgyrios Kyrtzidis case BO_Shr: 166fa0734ecSArgyrios Kyrtzidis case BO_Xor: 167fa0734ecSArgyrios Kyrtzidis // a+0, a-0, a<<0, a>>0, a^0 168fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 169fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 170fa0734ecSArgyrios Kyrtzidis break; 171fa0734ecSArgyrios Kyrtzidis case BO_And: 172fa0734ecSArgyrios Kyrtzidis // a&0 and a&(~0) 173fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 174fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 175d933adeaSJay Foad else if (RHS.isAllOnes()) 176fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 177fa0734ecSArgyrios Kyrtzidis break; 178fa0734ecSArgyrios Kyrtzidis case BO_Or: 179fa0734ecSArgyrios Kyrtzidis // a|0 and a|(~0) 180fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 181fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 182d933adeaSJay Foad else if (RHS.isAllOnes()) { 183fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS); 184fa0734ecSArgyrios Kyrtzidis return nonloc::ConcreteInt(Result); 185fa0734ecSArgyrios Kyrtzidis } 186fa0734ecSArgyrios Kyrtzidis break; 187fa0734ecSArgyrios Kyrtzidis } 188fa0734ecSArgyrios Kyrtzidis 189fa0734ecSArgyrios Kyrtzidis // Idempotent ops (like a*1) can still change the type of an expression. 19001ddfa95SDenys Petrov // Wrap the LHS up in a NonLoc again and let evalCast do the 1915ad574c0SZhanyong Wan // dirty work. 192d066f79cSAnna Zaks if (isIdempotent) 19301ddfa95SDenys Petrov return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{}); 194fa0734ecSArgyrios Kyrtzidis 195fa0734ecSArgyrios Kyrtzidis // If we reach this point, the expression cannot be simplified. 19654569448SJordy Rose // Make a SymbolVal for the entire expression, after converting the RHS. 19754569448SJordy Rose const llvm::APSInt *ConvertedRHS = &RHS; 19854569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) { 19954569448SJordy Rose // We're looking for a type big enough to compare the symbolic value 20054569448SJordy Rose // with the given constant. 20154569448SJordy Rose // FIXME: This is an approximation of Sema::UsualArithmeticConversions. 20254569448SJordy Rose ASTContext &Ctx = getContext(); 203a808e165STed Kremenek QualType SymbolType = LHS->getType(); 20454569448SJordy Rose uint64_t ValWidth = RHS.getBitWidth(); 20554569448SJordy Rose uint64_t TypeWidth = Ctx.getTypeSize(SymbolType); 20654569448SJordy Rose 20754569448SJordy Rose if (ValWidth < TypeWidth) { 20854569448SJordy Rose // If the value is too small, extend it. 20954569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS); 21054569448SJordy Rose } else if (ValWidth == TypeWidth) { 21154569448SJordy Rose // If the value is signed but the symbol is unsigned, do the comparison 21254569448SJordy Rose // in unsigned space. [C99 6.3.1.8] 21354569448SJordy Rose // (For the opposite case, the value is already unsigned.) 21454569448SJordy Rose if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType()) 21554569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS); 21654569448SJordy Rose } 217*14742443STomasz Kamiński } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) { 218*14742443STomasz Kamiński // Change a+(-N) into a-N, and a-(-N) into a+N 219*14742443STomasz Kamiński // Adjust addition/subtraction of negative value, to 220*14742443STomasz Kamiński // subtraction/addition of the negated value. 221*14742443STomasz Kamiński APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy); 222*14742443STomasz Kamiński if (isNegationValuePreserving(RHS, resultIntTy)) { 223*14742443STomasz Kamiński ConvertedRHS = &BasicVals.getValue(-resultIntTy.convert(RHS)); 224*14742443STomasz Kamiński op = (op == BO_Add) ? BO_Sub : BO_Add; 225*14742443STomasz Kamiński } else { 226*14742443STomasz Kamiński ConvertedRHS = &BasicVals.Convert(resultTy, RHS); 227*14742443STomasz Kamiński } 228da5b5ae8SBalazs Benics } else 22954569448SJordy Rose ConvertedRHS = &BasicVals.Convert(resultTy, RHS); 23054569448SJordy Rose 23154569448SJordy Rose return makeNonLoc(LHS, op, *ConvertedRHS, resultTy); 232fa0734ecSArgyrios Kyrtzidis } 233fa0734ecSArgyrios Kyrtzidis 2342bbccca9SAdam Balogh // See if Sym is known to be a relation Rel with Bound. 2352bbccca9SAdam Balogh static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym, 2362bbccca9SAdam Balogh llvm::APSInt Bound, ProgramStateRef State) { 2372bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 2382bbccca9SAdam Balogh SVal Result = 2392bbccca9SAdam Balogh SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym), 2402bbccca9SAdam Balogh nonloc::ConcreteInt(Bound), SVB.getConditionType()); 2412bbccca9SAdam Balogh if (auto DV = Result.getAs<DefinedSVal>()) { 2422bbccca9SAdam Balogh return !State->assume(*DV, false); 2432bbccca9SAdam Balogh } 2442bbccca9SAdam Balogh return false; 2452bbccca9SAdam Balogh } 2462bbccca9SAdam Balogh 2472bbccca9SAdam Balogh // See if Sym is known to be within [min/4, max/4], where min and max 2482bbccca9SAdam Balogh // are the bounds of the symbol's integral type. With such symbols, 2492bbccca9SAdam Balogh // some manipulations can be performed without the risk of overflow. 2502bbccca9SAdam Balogh // assume() doesn't cause infinite recursion because we should be dealing 2512bbccca9SAdam Balogh // with simpler symbols on every recursive call. 2522bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(SymbolRef Sym, 2532bbccca9SAdam Balogh ProgramStateRef State) { 2542bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 2552bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory(); 2562bbccca9SAdam Balogh 2572bbccca9SAdam Balogh QualType T = Sym->getType(); 2582bbccca9SAdam Balogh assert(T->isSignedIntegerOrEnumerationType() && 2592bbccca9SAdam Balogh "This only works with signed integers!"); 2602bbccca9SAdam Balogh APSIntType AT = BV.getAPSIntType(T); 2612bbccca9SAdam Balogh 2622bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max; 2632bbccca9SAdam Balogh return isInRelation(BO_LE, Sym, Max, State) && 2642bbccca9SAdam Balogh isInRelation(BO_GE, Sym, Min, State); 2652bbccca9SAdam Balogh } 2662bbccca9SAdam Balogh 2672bbccca9SAdam Balogh // Same for the concrete integers: see if I is within [min/4, max/4]. 2682bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(llvm::APSInt I) { 2692bbccca9SAdam Balogh APSIntType AT(I); 2702bbccca9SAdam Balogh assert(!AT.isUnsigned() && 2712bbccca9SAdam Balogh "This only works with signed integers!"); 2722bbccca9SAdam Balogh 2732bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max; 2742bbccca9SAdam Balogh return (I <= Max) && (I >= -Max); 2752bbccca9SAdam Balogh } 2762bbccca9SAdam Balogh 2772bbccca9SAdam Balogh static std::pair<SymbolRef, llvm::APSInt> 2782bbccca9SAdam Balogh decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) { 2792bbccca9SAdam Balogh if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym)) 2802bbccca9SAdam Balogh if (BinaryOperator::isAdditiveOp(SymInt->getOpcode())) 2812bbccca9SAdam Balogh return std::make_pair(SymInt->getLHS(), 2822bbccca9SAdam Balogh (SymInt->getOpcode() == BO_Add) ? 2832bbccca9SAdam Balogh (SymInt->getRHS()) : 2842bbccca9SAdam Balogh (-SymInt->getRHS())); 2852bbccca9SAdam Balogh 2862bbccca9SAdam Balogh // Fail to decompose: "reduce" the problem to the "$x + 0" case. 2872bbccca9SAdam Balogh return std::make_pair(Sym, BV.getValue(0, Sym->getType())); 2882bbccca9SAdam Balogh } 2892bbccca9SAdam Balogh 2902bbccca9SAdam Balogh // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the 2912bbccca9SAdam Balogh // same signed integral type and no overflows occur (which should be checked 2922bbccca9SAdam Balogh // by the caller). 2932bbccca9SAdam Balogh static NonLoc doRearrangeUnchecked(ProgramStateRef State, 2942bbccca9SAdam Balogh BinaryOperator::Opcode Op, 2952bbccca9SAdam Balogh SymbolRef LSym, llvm::APSInt LInt, 2962bbccca9SAdam Balogh SymbolRef RSym, llvm::APSInt RInt) { 2972bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 2982bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory(); 2992bbccca9SAdam Balogh SymbolManager &SymMgr = SVB.getSymbolManager(); 3002bbccca9SAdam Balogh 3012bbccca9SAdam Balogh QualType SymTy = LSym->getType(); 3022bbccca9SAdam Balogh assert(SymTy == RSym->getType() && 3032bbccca9SAdam Balogh "Symbols are not of the same type!"); 3042bbccca9SAdam Balogh assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) && 3052bbccca9SAdam Balogh "Integers are not of the same type as symbols!"); 3062bbccca9SAdam Balogh assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) && 3072bbccca9SAdam Balogh "Integers are not of the same type as symbols!"); 3082bbccca9SAdam Balogh 3092bbccca9SAdam Balogh QualType ResultTy; 3102bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op)) 3112bbccca9SAdam Balogh ResultTy = SVB.getConditionType(); 3122bbccca9SAdam Balogh else if (BinaryOperator::isAdditiveOp(Op)) 3132bbccca9SAdam Balogh ResultTy = SymTy; 3142bbccca9SAdam Balogh else 3152bbccca9SAdam Balogh llvm_unreachable("Operation not suitable for unchecked rearrangement!"); 3162bbccca9SAdam Balogh 3172bbccca9SAdam Balogh // FIXME: Can we use assume() without getting into an infinite recursion? 3182bbccca9SAdam Balogh if (LSym == RSym) 3192bbccca9SAdam Balogh return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt), 3202bbccca9SAdam Balogh nonloc::ConcreteInt(RInt), ResultTy) 3212bbccca9SAdam Balogh .castAs<NonLoc>(); 3222bbccca9SAdam Balogh 3232bbccca9SAdam Balogh SymbolRef ResultSym = nullptr; 3242bbccca9SAdam Balogh BinaryOperator::Opcode ResultOp; 3252bbccca9SAdam Balogh llvm::APSInt ResultInt; 3262bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op)) { 3272bbccca9SAdam Balogh // Prefer comparing to a non-negative number. 3282bbccca9SAdam Balogh // FIXME: Maybe it'd be better to have consistency in 3292bbccca9SAdam Balogh // "$x - $y" vs. "$y - $x" because those are solver's keys. 3302bbccca9SAdam Balogh if (LInt > RInt) { 3312bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy); 3322bbccca9SAdam Balogh ResultOp = BinaryOperator::reverseComparisonOp(Op); 3332bbccca9SAdam Balogh ResultInt = LInt - RInt; // Opposite order! 3342bbccca9SAdam Balogh } else { 3352bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy); 3362bbccca9SAdam Balogh ResultOp = Op; 3372bbccca9SAdam Balogh ResultInt = RInt - LInt; // Opposite order! 3382bbccca9SAdam Balogh } 3392bbccca9SAdam Balogh } else { 3402bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy); 3412bbccca9SAdam Balogh ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt); 3422bbccca9SAdam Balogh ResultOp = BO_Add; 3432bbccca9SAdam Balogh // Bring back the cosmetic difference. 3442bbccca9SAdam Balogh if (ResultInt < 0) { 3452bbccca9SAdam Balogh ResultInt = -ResultInt; 3462bbccca9SAdam Balogh ResultOp = BO_Sub; 3472bbccca9SAdam Balogh } else if (ResultInt == 0) { 3482bbccca9SAdam Balogh // Shortcut: Simplify "$x + 0" to "$x". 3492bbccca9SAdam Balogh return nonloc::SymbolVal(ResultSym); 3502bbccca9SAdam Balogh } 3512bbccca9SAdam Balogh } 3522bbccca9SAdam Balogh const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt); 3532bbccca9SAdam Balogh return nonloc::SymbolVal( 3542bbccca9SAdam Balogh SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy)); 3552bbccca9SAdam Balogh } 3562bbccca9SAdam Balogh 3572bbccca9SAdam Balogh // Rearrange if symbol type matches the result type and if the operator is a 3582bbccca9SAdam Balogh // comparison operator, both symbol and constant must be within constant 3592bbccca9SAdam Balogh // overflow bounds. 3602bbccca9SAdam Balogh static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op, 3612bbccca9SAdam Balogh SymbolRef Sym, llvm::APSInt Int, QualType Ty) { 3622bbccca9SAdam Balogh return Sym->getType() == Ty && 3632bbccca9SAdam Balogh (!BinaryOperator::isComparisonOp(Op) || 3642bbccca9SAdam Balogh (isWithinConstantOverflowBounds(Sym, State) && 3652bbccca9SAdam Balogh isWithinConstantOverflowBounds(Int))); 3662bbccca9SAdam Balogh } 3672bbccca9SAdam Balogh 3682bbccca9SAdam Balogh static Optional<NonLoc> tryRearrange(ProgramStateRef State, 3692bbccca9SAdam Balogh BinaryOperator::Opcode Op, NonLoc Lhs, 3702bbccca9SAdam Balogh NonLoc Rhs, QualType ResultTy) { 3712bbccca9SAdam Balogh ProgramStateManager &StateMgr = State->getStateManager(); 3722bbccca9SAdam Balogh SValBuilder &SVB = StateMgr.getSValBuilder(); 3732bbccca9SAdam Balogh 3742bbccca9SAdam Balogh // We expect everything to be of the same type - this type. 3752bbccca9SAdam Balogh QualType SingleTy; 3762bbccca9SAdam Balogh 377dcde8accSAdam Balogh // FIXME: After putting complexity threshold to the symbols we can always 378dcde8accSAdam Balogh // rearrange additive operations but rearrange comparisons only if 379dcde8accSAdam Balogh // option is set. 380b97a9640SBalazs Benics if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation) 381dcde8accSAdam Balogh return None; 382dcde8accSAdam Balogh 3832bbccca9SAdam Balogh SymbolRef LSym = Lhs.getAsSymbol(); 3842bbccca9SAdam Balogh if (!LSym) 3852bbccca9SAdam Balogh return None; 3862bbccca9SAdam Balogh 387dcde8accSAdam Balogh if (BinaryOperator::isComparisonOp(Op)) { 3882bbccca9SAdam Balogh SingleTy = LSym->getType(); 3892bbccca9SAdam Balogh if (ResultTy != SVB.getConditionType()) 3902bbccca9SAdam Balogh return None; 3912bbccca9SAdam Balogh // Initialize SingleTy later with a symbol's type. 3922bbccca9SAdam Balogh } else if (BinaryOperator::isAdditiveOp(Op)) { 3932bbccca9SAdam Balogh SingleTy = ResultTy; 39413e186c0SAdam Balogh if (LSym->getType() != SingleTy) 39513e186c0SAdam Balogh return None; 3962bbccca9SAdam Balogh } else { 3972bbccca9SAdam Balogh // Don't rearrange other operations. 3982bbccca9SAdam Balogh return None; 3992bbccca9SAdam Balogh } 4002bbccca9SAdam Balogh 4012bbccca9SAdam Balogh assert(!SingleTy.isNull() && "We should have figured out the type by now!"); 4022bbccca9SAdam Balogh 403471d0864SAdam Balogh // Rearrange signed symbolic expressions only 404471d0864SAdam Balogh if (!SingleTy->isSignedIntegerOrEnumerationType()) 405471d0864SAdam Balogh return None; 406471d0864SAdam Balogh 4072bbccca9SAdam Balogh SymbolRef RSym = Rhs.getAsSymbol(); 4082bbccca9SAdam Balogh if (!RSym || RSym->getType() != SingleTy) 4092bbccca9SAdam Balogh return None; 4102bbccca9SAdam Balogh 4112bbccca9SAdam Balogh BasicValueFactory &BV = State->getBasicVals(); 4122bbccca9SAdam Balogh llvm::APSInt LInt, RInt; 4132bbccca9SAdam Balogh std::tie(LSym, LInt) = decomposeSymbol(LSym, BV); 4142bbccca9SAdam Balogh std::tie(RSym, RInt) = decomposeSymbol(RSym, BV); 4152bbccca9SAdam Balogh if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) || 4162bbccca9SAdam Balogh !shouldRearrange(State, Op, RSym, RInt, SingleTy)) 4172bbccca9SAdam Balogh return None; 4182bbccca9SAdam Balogh 4192bbccca9SAdam Balogh // We know that no overflows can occur anymore. 4202bbccca9SAdam Balogh return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt); 4212bbccca9SAdam Balogh } 4222bbccca9SAdam Balogh 42349b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state, 424fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 425fa0734ecSArgyrios Kyrtzidis NonLoc lhs, NonLoc rhs, 426fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 427f0e9ca86SAnna Zaks NonLoc InputLHS = lhs; 428f0e9ca86SAnna Zaks NonLoc InputRHS = rhs; 429f0e9ca86SAnna Zaks 43012887a20SGabor Marton // Constraints may have changed since the creation of a bound SVal. Check if 43112887a20SGabor Marton // the values can be simplified based on those new constraints. 43212887a20SGabor Marton SVal simplifiedLhs = simplifySVal(state, lhs); 43312887a20SGabor Marton SVal simplifiedRhs = simplifySVal(state, rhs); 43412887a20SGabor Marton if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) 43512887a20SGabor Marton lhs = *simplifiedLhsAsNonLoc; 43612887a20SGabor Marton if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>()) 43712887a20SGabor Marton rhs = *simplifiedRhsAsNonLoc; 43812887a20SGabor Marton 439fa0734ecSArgyrios Kyrtzidis // Handle trivial case where left-side and right-side are the same. 440fa0734ecSArgyrios Kyrtzidis if (lhs == rhs) 441fa0734ecSArgyrios Kyrtzidis switch (op) { 442fa0734ecSArgyrios Kyrtzidis default: 443fa0734ecSArgyrios Kyrtzidis break; 444fa0734ecSArgyrios Kyrtzidis case BO_EQ: 445fa0734ecSArgyrios Kyrtzidis case BO_LE: 446fa0734ecSArgyrios Kyrtzidis case BO_GE: 447fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 448fa0734ecSArgyrios Kyrtzidis case BO_LT: 449fa0734ecSArgyrios Kyrtzidis case BO_GT: 450fa0734ecSArgyrios Kyrtzidis case BO_NE: 451fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 452fa0734ecSArgyrios Kyrtzidis case BO_Xor: 453fa0734ecSArgyrios Kyrtzidis case BO_Sub: 4547523d1a8SJordan Rose if (resultTy->isIntegralOrEnumerationType()) 455fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 45601ddfa95SDenys Petrov return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy, 45701ddfa95SDenys Petrov QualType{}); 458fa0734ecSArgyrios Kyrtzidis case BO_Or: 459fa0734ecSArgyrios Kyrtzidis case BO_And: 46001ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 461fa0734ecSArgyrios Kyrtzidis } 462fa0734ecSArgyrios Kyrtzidis 46340446663SKazu Hirata while (true) { 464fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) { 465fa0734ecSArgyrios Kyrtzidis default: 466bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, lhs, rhs, resultTy); 46764c01f7bSDevin Coughlin case nonloc::PointerToMemberKind: { 46864c01f7bSDevin Coughlin assert(rhs.getSubKind() == nonloc::PointerToMemberKind && 46964c01f7bSDevin Coughlin "Both SVals should have pointer-to-member-type"); 47064c01f7bSDevin Coughlin auto LPTM = lhs.castAs<nonloc::PointerToMember>(), 47164c01f7bSDevin Coughlin RPTM = rhs.castAs<nonloc::PointerToMember>(); 47264c01f7bSDevin Coughlin auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData(); 47364c01f7bSDevin Coughlin switch (op) { 47464c01f7bSDevin Coughlin case BO_EQ: 47564c01f7bSDevin Coughlin return makeTruthVal(LPTMD == RPTMD, resultTy); 47664c01f7bSDevin Coughlin case BO_NE: 47764c01f7bSDevin Coughlin return makeTruthVal(LPTMD != RPTMD, resultTy); 47864c01f7bSDevin Coughlin default: 47964c01f7bSDevin Coughlin return UnknownVal(); 48064c01f7bSDevin Coughlin } 48164c01f7bSDevin Coughlin } 482fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind: { 4832fdacbc5SDavid Blaikie Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc(); 484fa0734ecSArgyrios Kyrtzidis switch (rhs.getSubKind()) { 485fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind: 48618d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation 48718d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete. 48818d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op)) 48918d77984SAlexander Shaposhnikov return UnknownVal(); 490fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL, 4912fdacbc5SDavid Blaikie rhs.castAs<nonloc::LocAsInteger>().getLoc(), 492fa0734ecSArgyrios Kyrtzidis resultTy); 493fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: { 49418d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation 49518d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete. 49618d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op)) 49718d77984SAlexander Shaposhnikov return UnknownVal(); 498fa0734ecSArgyrios Kyrtzidis // Transform the integer into a location and compare. 4997333a9eaSArtem Dergachev // FIXME: This only makes sense for comparisons. If we want to, say, 5007333a9eaSArtem Dergachev // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it, 5017333a9eaSArtem Dergachev // then pack it back into a LocAsInteger. 5022fdacbc5SDavid Blaikie llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue(); 50327ed855aSDavid Stenberg // If the region has a symbolic base, pay attention to the type; it 50427ed855aSDavid Stenberg // might be coming from a non-default address space. For non-symbolic 50527ed855aSDavid Stenberg // regions it doesn't matter that much because such comparisons would 50627ed855aSDavid Stenberg // most likely evaluate to concrete false anyway. FIXME: We might 50727ed855aSDavid Stenberg // still need to handle the non-comparison case. 50827ed855aSDavid Stenberg if (SymbolRef lSym = lhs.getAsLocSymbol(true)) 50927ed855aSDavid Stenberg BasicVals.getAPSIntType(lSym->getType()).apply(i); 51027ed855aSDavid Stenberg else 5117e3c3ea3SJordy Rose BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i); 512fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy); 513fa0734ecSArgyrios Kyrtzidis } 514fa0734ecSArgyrios Kyrtzidis default: 515fa0734ecSArgyrios Kyrtzidis switch (op) { 516fa0734ecSArgyrios Kyrtzidis case BO_EQ: 517fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 518fa0734ecSArgyrios Kyrtzidis case BO_NE: 519fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 520fa0734ecSArgyrios Kyrtzidis default: 521fa0734ecSArgyrios Kyrtzidis // This case also handles pointer arithmetic. 522bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 523fa0734ecSArgyrios Kyrtzidis } 524fa0734ecSArgyrios Kyrtzidis } 525fa0734ecSArgyrios Kyrtzidis } 526d066f79cSAnna Zaks case nonloc::ConcreteIntKind: { 5272fdacbc5SDavid Blaikie llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue(); 528d066f79cSAnna Zaks 52954569448SJordy Rose // If we're dealing with two known constants, just perform the operation. 53054569448SJordy Rose if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) { 53154569448SJordy Rose llvm::APSInt RHSValue = *KnownRHSValue; 53254569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) { 53354569448SJordy Rose // We're looking for a type big enough to compare the two values. 5347e3c3ea3SJordy Rose // FIXME: This is not correct. char + short will result in a promotion 5357e3c3ea3SJordy Rose // to int. Unfortunately we have lost types by this point. 5367e3c3ea3SJordy Rose APSIntType CompareType = std::max(APSIntType(LHSValue), 5377e3c3ea3SJordy Rose APSIntType(RHSValue)); 5387e3c3ea3SJordy Rose CompareType.apply(LHSValue); 5397e3c3ea3SJordy Rose CompareType.apply(RHSValue); 54054569448SJordy Rose } else if (!BinaryOperator::isShiftOp(op)) { 5417e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy); 5427e3c3ea3SJordy Rose IntType.apply(LHSValue); 5437e3c3ea3SJordy Rose IntType.apply(RHSValue); 544d066f79cSAnna Zaks } 545d066f79cSAnna Zaks 54654569448SJordy Rose const llvm::APSInt *Result = 54754569448SJordy Rose BasicVals.evalAPSInt(op, LHSValue, RHSValue); 54854569448SJordy Rose if (!Result) 54954569448SJordy Rose return UndefinedVal(); 55054569448SJordy Rose 55154569448SJordy Rose return nonloc::ConcreteInt(*Result); 55254569448SJordy Rose } 553d066f79cSAnna Zaks 554d066f79cSAnna Zaks // Swap the left and right sides and flip the operator if doing so 555d066f79cSAnna Zaks // allows us to better reason about the expression (this is a form 556d066f79cSAnna Zaks // of expression canonicalization). 557d066f79cSAnna Zaks // While we're at it, catch some special cases for non-commutative ops. 558d066f79cSAnna Zaks switch (op) { 559d066f79cSAnna Zaks case BO_LT: 560d066f79cSAnna Zaks case BO_GT: 561d066f79cSAnna Zaks case BO_LE: 562d066f79cSAnna Zaks case BO_GE: 563604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op); 5644dc0b1acSReid Kleckner LLVM_FALLTHROUGH; 565d066f79cSAnna Zaks case BO_EQ: 566d066f79cSAnna Zaks case BO_NE: 567d066f79cSAnna Zaks case BO_Add: 568d066f79cSAnna Zaks case BO_Mul: 569d066f79cSAnna Zaks case BO_And: 570d066f79cSAnna Zaks case BO_Xor: 571d066f79cSAnna Zaks case BO_Or: 57254569448SJordy Rose std::swap(lhs, rhs); 573d066f79cSAnna Zaks continue; 574d066f79cSAnna Zaks case BO_Shr: 57554569448SJordy Rose // (~0)>>a 576d933adeaSJay Foad if (LHSValue.isAllOnes() && LHSValue.isSigned()) 57701ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 5784dc0b1acSReid Kleckner LLVM_FALLTHROUGH; 579d066f79cSAnna Zaks case BO_Shl: 58054569448SJordy Rose // 0<<a and 0>>a 58154569448SJordy Rose if (LHSValue == 0) 58201ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 583bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 584015c3988SGabor Marton case BO_Div: 585015c3988SGabor Marton // 0 / x == 0 58673c120a9SValeriy Savchenko case BO_Rem: 58773c120a9SValeriy Savchenko // 0 % x == 0 58873c120a9SValeriy Savchenko if (LHSValue == 0) 58973c120a9SValeriy Savchenko return makeZeroVal(resultTy); 59073c120a9SValeriy Savchenko LLVM_FALLTHROUGH; 591d066f79cSAnna Zaks default: 592bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 593d066f79cSAnna Zaks } 594d066f79cSAnna Zaks } 595d066f79cSAnna Zaks case nonloc::SymbolValKind: { 59654569448SJordy Rose // We only handle LHS as simple symbols or SymIntExprs. 5972fdacbc5SDavid Blaikie SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol(); 598d066f79cSAnna Zaks 599d066f79cSAnna Zaks // LHS is a symbolic expression. 60054569448SJordy Rose if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) { 601fa0734ecSArgyrios Kyrtzidis 602fa0734ecSArgyrios Kyrtzidis // Is this a logical not? (!x is represented as x == 0.) 603fa0734ecSArgyrios Kyrtzidis if (op == BO_EQ && rhs.isZeroConstant()) { 604fa0734ecSArgyrios Kyrtzidis // We know how to negate certain expressions. Simplify them here. 605fa0734ecSArgyrios Kyrtzidis 606fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode opc = symIntExpr->getOpcode(); 607fa0734ecSArgyrios Kyrtzidis switch (opc) { 608fa0734ecSArgyrios Kyrtzidis default: 609fa0734ecSArgyrios Kyrtzidis // We don't know how to negate this operation. 610fa0734ecSArgyrios Kyrtzidis // Just handle it as if it were a normal comparison to 0. 611fa0734ecSArgyrios Kyrtzidis break; 612fa0734ecSArgyrios Kyrtzidis case BO_LAnd: 613fa0734ecSArgyrios Kyrtzidis case BO_LOr: 61483d382b1SDavid Blaikie llvm_unreachable("Logical operators handled by branching logic."); 615fa0734ecSArgyrios Kyrtzidis case BO_Assign: 616fa0734ecSArgyrios Kyrtzidis case BO_MulAssign: 617fa0734ecSArgyrios Kyrtzidis case BO_DivAssign: 618fa0734ecSArgyrios Kyrtzidis case BO_RemAssign: 619fa0734ecSArgyrios Kyrtzidis case BO_AddAssign: 620fa0734ecSArgyrios Kyrtzidis case BO_SubAssign: 621fa0734ecSArgyrios Kyrtzidis case BO_ShlAssign: 622fa0734ecSArgyrios Kyrtzidis case BO_ShrAssign: 623fa0734ecSArgyrios Kyrtzidis case BO_AndAssign: 624fa0734ecSArgyrios Kyrtzidis case BO_XorAssign: 625fa0734ecSArgyrios Kyrtzidis case BO_OrAssign: 626fa0734ecSArgyrios Kyrtzidis case BO_Comma: 62783d382b1SDavid Blaikie llvm_unreachable("'=' and ',' operators handled by ExprEngine."); 628fa0734ecSArgyrios Kyrtzidis case BO_PtrMemD: 629fa0734ecSArgyrios Kyrtzidis case BO_PtrMemI: 63083d382b1SDavid Blaikie llvm_unreachable("Pointer arithmetic not handled here."); 631fa0734ecSArgyrios Kyrtzidis case BO_LT: 632fa0734ecSArgyrios Kyrtzidis case BO_GT: 633fa0734ecSArgyrios Kyrtzidis case BO_LE: 634fa0734ecSArgyrios Kyrtzidis case BO_GE: 635fa0734ecSArgyrios Kyrtzidis case BO_EQ: 636fa0734ecSArgyrios Kyrtzidis case BO_NE: 637dc16628cSJordan Rose assert(resultTy->isBooleanType() || 638dc16628cSJordan Rose resultTy == getConditionType()); 639dc16628cSJordan Rose assert(symIntExpr->getType()->isBooleanType() || 640dc16628cSJordan Rose getContext().hasSameUnqualifiedType(symIntExpr->getType(), 641dc16628cSJordan Rose getConditionType())); 642fa0734ecSArgyrios Kyrtzidis // Negate the comparison and make a value. 643604d0bbbSJordan Rose opc = BinaryOperator::negateComparisonOp(opc); 644fa0734ecSArgyrios Kyrtzidis return makeNonLoc(symIntExpr->getLHS(), opc, 645fa0734ecSArgyrios Kyrtzidis symIntExpr->getRHS(), resultTy); 646fa0734ecSArgyrios Kyrtzidis } 647fa0734ecSArgyrios Kyrtzidis } 648fa0734ecSArgyrios Kyrtzidis 649fa0734ecSArgyrios Kyrtzidis // For now, only handle expressions whose RHS is a constant. 65054569448SJordy Rose if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) { 651fa0734ecSArgyrios Kyrtzidis // If both the LHS and the current expression are additive, 65254569448SJordy Rose // fold their constants and try again. 653fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(op)) { 654fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode lop = symIntExpr->getOpcode(); 655fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(lop)) { 65654569448SJordy Rose // Convert the two constants to a common type, then combine them. 65754569448SJordy Rose 658fa0734ecSArgyrios Kyrtzidis // resultTy may not be the best type to convert to, but it's 659fa0734ecSArgyrios Kyrtzidis // probably the best choice in expressions with mixed type 660fa0734ecSArgyrios Kyrtzidis // (such as x+1U+2LL). The rules for implicit conversions should 661fa0734ecSArgyrios Kyrtzidis // choose a reasonable type to preserve the expression, and will 662fa0734ecSArgyrios Kyrtzidis // at least match how the value is going to be used. 6637e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy); 6647e3c3ea3SJordy Rose const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS()); 6657e3c3ea3SJordy Rose const llvm::APSInt &second = IntType.convert(*RHSValue); 66654569448SJordy Rose 667*14742443STomasz Kamiński // If the op and lop agrees, then we just need to 668*14742443STomasz Kamiński // sum the constants. Otherwise, we change to operation 669*14742443STomasz Kamiński // type if substraction would produce negative value 670*14742443STomasz Kamiński // (and cause overflow for unsigned integers), 671*14742443STomasz Kamiński // as consequence x+1U-10 produces x-9U, instead 672*14742443STomasz Kamiński // of x+4294967287U, that would be produced without this 673*14742443STomasz Kamiński // additional check. 674fa0734ecSArgyrios Kyrtzidis const llvm::APSInt *newRHS; 675*14742443STomasz Kamiński if (lop == op) { 676fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Add, first, second); 677*14742443STomasz Kamiński } else if (first >= second) { 678fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Sub, first, second); 679*14742443STomasz Kamiński op = lop; 680*14742443STomasz Kamiński } else { 681*14742443STomasz Kamiński newRHS = BasicVals.evalAPSInt(BO_Sub, second, first); 682*14742443STomasz Kamiński } 68354569448SJordy Rose 68454569448SJordy Rose assert(newRHS && "Invalid operation despite common type!"); 68554569448SJordy Rose rhs = nonloc::ConcreteInt(*newRHS); 68654569448SJordy Rose lhs = nonloc::SymbolVal(symIntExpr->getLHS()); 68754569448SJordy Rose continue; 688fa0734ecSArgyrios Kyrtzidis } 689fa0734ecSArgyrios Kyrtzidis } 690fa0734ecSArgyrios Kyrtzidis 69154569448SJordy Rose // Otherwise, make a SymIntExpr out of the expression. 69254569448SJordy Rose return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy); 69354569448SJordy Rose } 6943b4c3ea2SJordan Rose } 695fa0734ecSArgyrios Kyrtzidis 69654569448SJordy Rose // Is the RHS a constant? 69754569448SJordy Rose if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) 69854569448SJordy Rose return MakeSymIntVal(Sym, op, *RHSValue, resultTy); 699fa0734ecSArgyrios Kyrtzidis 7002bbccca9SAdam Balogh if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy)) 7012bbccca9SAdam Balogh return *V; 7022bbccca9SAdam Balogh 70354569448SJordy Rose // Give up -- this is not a symbolic expression we can handle. 704bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 705fa0734ecSArgyrios Kyrtzidis } 706fa0734ecSArgyrios Kyrtzidis } 707fa0734ecSArgyrios Kyrtzidis } 708fa0734ecSArgyrios Kyrtzidis } 709fa0734ecSArgyrios Kyrtzidis 710bac964e1SAnna Zaks static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR, 711bac964e1SAnna Zaks const FieldRegion *RightFR, 712bac964e1SAnna Zaks BinaryOperator::Opcode op, 713bac964e1SAnna Zaks QualType resultTy, 714bac964e1SAnna Zaks SimpleSValBuilder &SVB) { 715bac964e1SAnna Zaks // Only comparisons are meaningful here! 716bac964e1SAnna Zaks if (!BinaryOperator::isComparisonOp(op)) 717bac964e1SAnna Zaks return UnknownVal(); 718bac964e1SAnna Zaks 719bac964e1SAnna Zaks // Next, see if the two FRs have the same super-region. 720bac964e1SAnna Zaks // FIXME: This doesn't handle casts yet, and simply stripping the casts 721bac964e1SAnna Zaks // doesn't help. 722bac964e1SAnna Zaks if (LeftFR->getSuperRegion() != RightFR->getSuperRegion()) 723bac964e1SAnna Zaks return UnknownVal(); 724bac964e1SAnna Zaks 725bac964e1SAnna Zaks const FieldDecl *LeftFD = LeftFR->getDecl(); 726bac964e1SAnna Zaks const FieldDecl *RightFD = RightFR->getDecl(); 727bac964e1SAnna Zaks const RecordDecl *RD = LeftFD->getParent(); 728bac964e1SAnna Zaks 729bac964e1SAnna Zaks // Make sure the two FRs are from the same kind of record. Just in case! 730bac964e1SAnna Zaks // FIXME: This is probably where inheritance would be a problem. 731bac964e1SAnna Zaks if (RD != RightFD->getParent()) 732bac964e1SAnna Zaks return UnknownVal(); 733bac964e1SAnna Zaks 734bac964e1SAnna Zaks // We know for sure that the two fields are not the same, since that 735bac964e1SAnna Zaks // would have given us the same SVal. 736bac964e1SAnna Zaks if (op == BO_EQ) 737bac964e1SAnna Zaks return SVB.makeTruthVal(false, resultTy); 738bac964e1SAnna Zaks if (op == BO_NE) 739bac964e1SAnna Zaks return SVB.makeTruthVal(true, resultTy); 740bac964e1SAnna Zaks 741bac964e1SAnna Zaks // Iterate through the fields and see which one comes first. 742bac964e1SAnna Zaks // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field 743bac964e1SAnna Zaks // members and the units in which bit-fields reside have addresses that 744bac964e1SAnna Zaks // increase in the order in which they are declared." 745bac964e1SAnna Zaks bool leftFirst = (op == BO_LT || op == BO_LE); 746e8a8baefSAaron Ballman for (const auto *I : RD->fields()) { 747e8a8baefSAaron Ballman if (I == LeftFD) 748bac964e1SAnna Zaks return SVB.makeTruthVal(leftFirst, resultTy); 749e8a8baefSAaron Ballman if (I == RightFD) 750bac964e1SAnna Zaks return SVB.makeTruthVal(!leftFirst, resultTy); 751bac964e1SAnna Zaks } 752bac964e1SAnna Zaks 753bac964e1SAnna Zaks llvm_unreachable("Fields not found in parent record's definition"); 754bac964e1SAnna Zaks } 755bac964e1SAnna Zaks 7564d5b824eSVince Bridgers // This is used in debug builds only for now because some downstream users 7574d5b824eSVince Bridgers // may hit this assert in their subsequent merges. 7584d5b824eSVince Bridgers // There are still places in the analyzer where equal bitwidth Locs 7594d5b824eSVince Bridgers // are compared, and need to be found and corrected. Recent previous fixes have 7604d5b824eSVince Bridgers // addressed the known problems of making NULLs with specific bitwidths 7614d5b824eSVince Bridgers // for Loc comparisons along with deprecation of APIs for the same purpose. 7624d5b824eSVince Bridgers // 7634d5b824eSVince Bridgers static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc, 7644d5b824eSVince Bridgers Loc LhsLoc) { 7654d5b824eSVince Bridgers // Implements a "best effort" check for RhsLoc and LhsLoc bit widths 7664d5b824eSVince Bridgers ASTContext &Ctx = State->getStateManager().getContext(); 7674d5b824eSVince Bridgers uint64_t RhsBitwidth = 7684d5b824eSVince Bridgers RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx)); 7694d5b824eSVince Bridgers uint64_t LhsBitwidth = 7704d5b824eSVince Bridgers LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx)); 7714d5b824eSVince Bridgers if (RhsBitwidth && LhsBitwidth && 7724d5b824eSVince Bridgers (LhsLoc.getSubKind() == RhsLoc.getSubKind())) { 7734d5b824eSVince Bridgers assert(RhsBitwidth == LhsBitwidth && 7744d5b824eSVince Bridgers "RhsLoc and LhsLoc bitwidth must be same!"); 7754d5b824eSVince Bridgers } 7764d5b824eSVince Bridgers } 7774d5b824eSVince Bridgers 778fa0734ecSArgyrios Kyrtzidis // FIXME: all this logic will change if/when we have MemRegion::getLocation(). 77949b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, 780fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 781fa0734ecSArgyrios Kyrtzidis Loc lhs, Loc rhs, 782fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 7834d5b824eSVince Bridgers 7844d5b824eSVince Bridgers // Assert that bitwidth of lhs and rhs are the same. 7854d5b824eSVince Bridgers // This can happen if two different address spaces are used, 7864d5b824eSVince Bridgers // and the bitwidths of the address spaces are different. 7874d5b824eSVince Bridgers // See LIT case clang/test/Analysis/cstring-checker-addressspace.c 7884d5b824eSVince Bridgers // FIXME: See comment above in the function assertEqualBitWidths 7894d5b824eSVince Bridgers assertEqualBitWidths(state, rhs, lhs); 7904d5b824eSVince Bridgers 791fa0734ecSArgyrios Kyrtzidis // Only comparisons and subtractions are valid operations on two pointers. 792fa0734ecSArgyrios Kyrtzidis // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15]. 793fa0734ecSArgyrios Kyrtzidis // However, if a pointer is casted to an integer, evalBinOpNN may end up 794fa0734ecSArgyrios Kyrtzidis // calling this function with another operation (PR7527). We don't attempt to 795fa0734ecSArgyrios Kyrtzidis // model this for now, but it could be useful, particularly when the 796fa0734ecSArgyrios Kyrtzidis // "location" is actually an integer value that's been passed through a void*. 797fa0734ecSArgyrios Kyrtzidis if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub)) 798fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 799fa0734ecSArgyrios Kyrtzidis 800fa0734ecSArgyrios Kyrtzidis // Special cases for when both sides are identical. 801fa0734ecSArgyrios Kyrtzidis if (lhs == rhs) { 802fa0734ecSArgyrios Kyrtzidis switch (op) { 803fa0734ecSArgyrios Kyrtzidis default: 80483d382b1SDavid Blaikie llvm_unreachable("Unimplemented operation for two identical values"); 805fa0734ecSArgyrios Kyrtzidis case BO_Sub: 806fa0734ecSArgyrios Kyrtzidis return makeZeroVal(resultTy); 807fa0734ecSArgyrios Kyrtzidis case BO_EQ: 808fa0734ecSArgyrios Kyrtzidis case BO_LE: 809fa0734ecSArgyrios Kyrtzidis case BO_GE: 810fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 811fa0734ecSArgyrios Kyrtzidis case BO_NE: 812fa0734ecSArgyrios Kyrtzidis case BO_LT: 813fa0734ecSArgyrios Kyrtzidis case BO_GT: 814fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 815fa0734ecSArgyrios Kyrtzidis } 816fa0734ecSArgyrios Kyrtzidis } 817fa0734ecSArgyrios Kyrtzidis 818fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) { 819fa0734ecSArgyrios Kyrtzidis default: 82083d382b1SDavid Blaikie llvm_unreachable("Ordering not implemented for this Loc."); 821fa0734ecSArgyrios Kyrtzidis 822fa0734ecSArgyrios Kyrtzidis case loc::GotoLabelKind: 823fa0734ecSArgyrios Kyrtzidis // The only thing we know about labels is that they're non-null. 824fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant()) { 825fa0734ecSArgyrios Kyrtzidis switch (op) { 826fa0734ecSArgyrios Kyrtzidis default: 827fa0734ecSArgyrios Kyrtzidis break; 828fa0734ecSArgyrios Kyrtzidis case BO_Sub: 82901ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 830fa0734ecSArgyrios Kyrtzidis case BO_EQ: 831fa0734ecSArgyrios Kyrtzidis case BO_LE: 832fa0734ecSArgyrios Kyrtzidis case BO_LT: 833fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 834fa0734ecSArgyrios Kyrtzidis case BO_NE: 835fa0734ecSArgyrios Kyrtzidis case BO_GT: 836fa0734ecSArgyrios Kyrtzidis case BO_GE: 837fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 838fa0734ecSArgyrios Kyrtzidis } 839fa0734ecSArgyrios Kyrtzidis } 840fa0734ecSArgyrios Kyrtzidis // There may be two labels for the same location, and a function region may 841fa0734ecSArgyrios Kyrtzidis // have the same address as a label at the start of the function (depending 842fa0734ecSArgyrios Kyrtzidis // on the ABI). 843fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably do a comparison against other MemRegions, though. 844fa0734ecSArgyrios Kyrtzidis // FIXME: is there a way to tell if two labels refer to the same location? 845fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 846fa0734ecSArgyrios Kyrtzidis 847fa0734ecSArgyrios Kyrtzidis case loc::ConcreteIntKind: { 848fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant, 849fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager. 850fa0734ecSArgyrios Kyrtzidis if (SymbolRef rSym = rhs.getAsLocSymbol()) { 851c0402c69SDominic Chen // We can only build expressions with symbols on the left, 852c0402c69SDominic Chen // so we need a reversible operator. 853c70f1d63SRichard Smith if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp) 854c0402c69SDominic Chen return UnknownVal(); 85535610d21SDominic Chen 856c0402c69SDominic Chen const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue(); 857604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op); 858604d0bbbSJordan Rose return makeNonLoc(rSym, op, lVal, resultTy); 859fa0734ecSArgyrios Kyrtzidis } 860fa0734ecSArgyrios Kyrtzidis 861fa0734ecSArgyrios Kyrtzidis // If both operands are constants, just perform the operation. 86205785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { 8632fdacbc5SDavid Blaikie SVal ResultVal = 8642fdacbc5SDavid Blaikie lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt); 8658eca04b2SJordan Rose if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>()) 86601ddfa95SDenys Petrov return evalCast(*Result, resultTy, QualType{}); 8678eca04b2SJordan Rose 8688eca04b2SJordan Rose assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs"); 869fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 870fa0734ecSArgyrios Kyrtzidis } 871fa0734ecSArgyrios Kyrtzidis 872fa0734ecSArgyrios Kyrtzidis // Special case comparisons against NULL. 873fa0734ecSArgyrios Kyrtzidis // This must come after the test if the RHS is a symbol, which is used to 874fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed 875fa0734ecSArgyrios Kyrtzidis // to be non-NULL, as is any label. 8762fdacbc5SDavid Blaikie assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>()); 877fa0734ecSArgyrios Kyrtzidis if (lhs.isZeroConstant()) { 878fa0734ecSArgyrios Kyrtzidis switch (op) { 879fa0734ecSArgyrios Kyrtzidis default: 880fa0734ecSArgyrios Kyrtzidis break; 881fa0734ecSArgyrios Kyrtzidis case BO_EQ: 882fa0734ecSArgyrios Kyrtzidis case BO_GT: 883fa0734ecSArgyrios Kyrtzidis case BO_GE: 884fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 885fa0734ecSArgyrios Kyrtzidis case BO_NE: 886fa0734ecSArgyrios Kyrtzidis case BO_LT: 887fa0734ecSArgyrios Kyrtzidis case BO_LE: 888fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 889fa0734ecSArgyrios Kyrtzidis } 890fa0734ecSArgyrios Kyrtzidis } 891fa0734ecSArgyrios Kyrtzidis 892fa0734ecSArgyrios Kyrtzidis // Comparing an arbitrary integer to a region or label address is 893fa0734ecSArgyrios Kyrtzidis // completely unknowable. 894fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 895fa0734ecSArgyrios Kyrtzidis } 89673f018e3SArtem Dergachev case loc::MemRegionValKind: { 89705785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { 898fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant, 899fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager. 900f4963ff1SAlexander Shaposhnikov if (SymbolRef lSym = lhs.getAsLocSymbol(true)) { 901f4963ff1SAlexander Shaposhnikov if (BinaryOperator::isComparisonOp(op)) 902fa0734ecSArgyrios Kyrtzidis return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy); 903f4963ff1SAlexander Shaposhnikov return UnknownVal(); 904f4963ff1SAlexander Shaposhnikov } 905fa0734ecSArgyrios Kyrtzidis // Special case comparisons to NULL. 906fa0734ecSArgyrios Kyrtzidis // This must come after the test if the LHS is a symbol, which is used to 907fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed 908fa0734ecSArgyrios Kyrtzidis // to be non-NULL. 909fa0734ecSArgyrios Kyrtzidis if (rInt->isZeroConstant()) { 910acd080b9SJordan Rose if (op == BO_Sub) 91101ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 912acd080b9SJordan Rose 913acd080b9SJordan Rose if (BinaryOperator::isComparisonOp(op)) { 914acd080b9SJordan Rose QualType boolType = getContext().BoolTy; 91501ddfa95SDenys Petrov NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>(); 916acd080b9SJordan Rose NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>(); 917acd080b9SJordan Rose return evalBinOpNN(state, op, l, r, resultTy); 918fa0734ecSArgyrios Kyrtzidis } 919fa0734ecSArgyrios Kyrtzidis } 920fa0734ecSArgyrios Kyrtzidis 921fa0734ecSArgyrios Kyrtzidis // Comparing a region to an arbitrary integer is completely unknowable. 922fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 923fa0734ecSArgyrios Kyrtzidis } 924fa0734ecSArgyrios Kyrtzidis 925fa0734ecSArgyrios Kyrtzidis // Get both values as regions, if possible. 926fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftMR = lhs.getAsRegion(); 92773f018e3SArtem Dergachev assert(LeftMR && "MemRegionValKind SVal doesn't have a region!"); 928fa0734ecSArgyrios Kyrtzidis 929fa0734ecSArgyrios Kyrtzidis const MemRegion *RightMR = rhs.getAsRegion(); 930fa0734ecSArgyrios Kyrtzidis if (!RightMR) 931fa0734ecSArgyrios Kyrtzidis // The RHS is probably a label, which in theory could address a region. 932fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably make a more useful statement about non-code 933fa0734ecSArgyrios Kyrtzidis // regions, though. 934fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 935fa0734ecSArgyrios Kyrtzidis 936fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftBase = LeftMR->getBaseRegion(); 937fa0734ecSArgyrios Kyrtzidis const MemRegion *RightBase = RightMR->getBaseRegion(); 9383b4c3ea2SJordan Rose const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace(); 9393b4c3ea2SJordan Rose const MemSpaceRegion *RightMS = RightBase->getMemorySpace(); 9403b4c3ea2SJordan Rose const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion(); 9413563fde6SAnna Zaks 9423563fde6SAnna Zaks // If the two regions are from different known memory spaces they cannot be 9433563fde6SAnna Zaks // equal. Also, assume that no symbolic region (whose memory space is 9443563fde6SAnna Zaks // unknown) is on the stack. 9453563fde6SAnna Zaks if (LeftMS != RightMS && 9463563fde6SAnna Zaks ((LeftMS != UnknownMS && RightMS != UnknownMS) || 9473563fde6SAnna Zaks (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) { 948fa0734ecSArgyrios Kyrtzidis switch (op) { 949fa0734ecSArgyrios Kyrtzidis default: 950fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 951fa0734ecSArgyrios Kyrtzidis case BO_EQ: 952fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 953fa0734ecSArgyrios Kyrtzidis case BO_NE: 954fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 955fa0734ecSArgyrios Kyrtzidis } 956fa0734ecSArgyrios Kyrtzidis } 957fa0734ecSArgyrios Kyrtzidis 9583563fde6SAnna Zaks // If both values wrap regions, see if they're from different base regions. 9593563fde6SAnna Zaks // Note, heap base symbolic regions are assumed to not alias with 9603563fde6SAnna Zaks // each other; for example, we assume that malloc returns different address 9613563fde6SAnna Zaks // on each invocation. 962aacc03c9SArtem Dergachev // FIXME: ObjC object pointers always reside on the heap, but currently 963aacc03c9SArtem Dergachev // we treat their memory space as unknown, because symbolic pointers 964aacc03c9SArtem Dergachev // to ObjC objects may alias. There should be a way to construct 965aacc03c9SArtem Dergachev // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker 966aacc03c9SArtem Dergachev // guesses memory space for ObjC object pointers manually instead of 967aacc03c9SArtem Dergachev // relying on us. 9683563fde6SAnna Zaks if (LeftBase != RightBase && 9693563fde6SAnna Zaks ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) || 970a7dcc996SAnna Zaks (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){ 9719d96f843STed Kremenek switch (op) { 9729d96f843STed Kremenek default: 9733563fde6SAnna Zaks return UnknownVal(); 9749d96f843STed Kremenek case BO_EQ: 9759d96f843STed Kremenek return makeTruthVal(false, resultTy); 9769d96f843STed Kremenek case BO_NE: 9779d96f843STed Kremenek return makeTruthVal(true, resultTy); 9789d96f843STed Kremenek } 9799d96f843STed Kremenek } 980fa0734ecSArgyrios Kyrtzidis 981bac964e1SAnna Zaks // Handle special cases for when both regions are element regions. 982fa0734ecSArgyrios Kyrtzidis const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR); 983bac964e1SAnna Zaks const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR); 984bac964e1SAnna Zaks if (RightER && LeftER) { 985fa0734ecSArgyrios Kyrtzidis // Next, see if the two ERs have the same super-region and matching types. 986fa0734ecSArgyrios Kyrtzidis // FIXME: This should do something useful even if the types don't match, 987fa0734ecSArgyrios Kyrtzidis // though if both indexes are constant the RegionRawOffset path will 988fa0734ecSArgyrios Kyrtzidis // give the correct answer. 989fa0734ecSArgyrios Kyrtzidis if (LeftER->getSuperRegion() == RightER->getSuperRegion() && 990fa0734ecSArgyrios Kyrtzidis LeftER->getElementType() == RightER->getElementType()) { 991fa0734ecSArgyrios Kyrtzidis // Get the left index and cast it to the correct type. 992fa0734ecSArgyrios Kyrtzidis // If the index is unknown or undefined, bail out here. 993fa0734ecSArgyrios Kyrtzidis SVal LeftIndexVal = LeftER->getIndex(); 99405785d16SDavid Blaikie Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>(); 995fa0734ecSArgyrios Kyrtzidis if (!LeftIndex) 996fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 99701ddfa95SDenys Petrov LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{}); 9982fdacbc5SDavid Blaikie LeftIndex = LeftIndexVal.getAs<NonLoc>(); 999fa0734ecSArgyrios Kyrtzidis if (!LeftIndex) 1000fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1001fa0734ecSArgyrios Kyrtzidis 1002fa0734ecSArgyrios Kyrtzidis // Do the same for the right index. 1003fa0734ecSArgyrios Kyrtzidis SVal RightIndexVal = RightER->getIndex(); 100405785d16SDavid Blaikie Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>(); 1005fa0734ecSArgyrios Kyrtzidis if (!RightIndex) 1006fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 100701ddfa95SDenys Petrov RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{}); 10082fdacbc5SDavid Blaikie RightIndex = RightIndexVal.getAs<NonLoc>(); 1009fa0734ecSArgyrios Kyrtzidis if (!RightIndex) 1010fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1011fa0734ecSArgyrios Kyrtzidis 1012fa0734ecSArgyrios Kyrtzidis // Actually perform the operation. 1013fa0734ecSArgyrios Kyrtzidis // evalBinOpNN expects the two indexes to already be the right type. 1014fa0734ecSArgyrios Kyrtzidis return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy); 1015fa0734ecSArgyrios Kyrtzidis } 1016bac964e1SAnna Zaks } 1017fa0734ecSArgyrios Kyrtzidis 1018bac964e1SAnna Zaks // Special handling of the FieldRegions, even with symbolic offsets. 1019bac964e1SAnna Zaks const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR); 1020bac964e1SAnna Zaks const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR); 1021bac964e1SAnna Zaks if (RightFR && LeftFR) { 1022bac964e1SAnna Zaks SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy, 1023bac964e1SAnna Zaks *this); 1024bac964e1SAnna Zaks if (!R.isUnknown()) 1025bac964e1SAnna Zaks return R; 1026bac964e1SAnna Zaks } 1027bac964e1SAnna Zaks 1028bac964e1SAnna Zaks // Compare the regions using the raw offsets. 1029bac964e1SAnna Zaks RegionOffset LeftOffset = LeftMR->getAsOffset(); 1030bac964e1SAnna Zaks RegionOffset RightOffset = RightMR->getAsOffset(); 1031fa0734ecSArgyrios Kyrtzidis 10320dbb783cSCraig Topper if (LeftOffset.getRegion() != nullptr && 1033bac964e1SAnna Zaks LeftOffset.getRegion() == RightOffset.getRegion() && 1034bac964e1SAnna Zaks !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) { 1035bac964e1SAnna Zaks int64_t left = LeftOffset.getOffset(); 1036bac964e1SAnna Zaks int64_t right = RightOffset.getOffset(); 1037fa0734ecSArgyrios Kyrtzidis 1038fa0734ecSArgyrios Kyrtzidis switch (op) { 1039fa0734ecSArgyrios Kyrtzidis default: 1040fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1041fa0734ecSArgyrios Kyrtzidis case BO_LT: 1042fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left < right, resultTy); 1043fa0734ecSArgyrios Kyrtzidis case BO_GT: 1044fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left > right, resultTy); 1045fa0734ecSArgyrios Kyrtzidis case BO_LE: 1046fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left <= right, resultTy); 1047fa0734ecSArgyrios Kyrtzidis case BO_GE: 1048fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left >= right, resultTy); 1049fa0734ecSArgyrios Kyrtzidis case BO_EQ: 1050fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left == right, resultTy); 1051fa0734ecSArgyrios Kyrtzidis case BO_NE: 1052fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left != right, resultTy); 1053fa0734ecSArgyrios Kyrtzidis } 1054fa0734ecSArgyrios Kyrtzidis } 1055fa0734ecSArgyrios Kyrtzidis 10563b4c3ea2SJordan Rose // At this point we're not going to get a good answer, but we can try 10573b4c3ea2SJordan Rose // conjuring an expression instead. 10583b4c3ea2SJordan Rose SymbolRef LHSSym = lhs.getAsLocSymbol(); 10593b4c3ea2SJordan Rose SymbolRef RHSSym = rhs.getAsLocSymbol(); 10603b4c3ea2SJordan Rose if (LHSSym && RHSSym) 10613b4c3ea2SJordan Rose return makeNonLoc(LHSSym, op, RHSSym, resultTy); 10623b4c3ea2SJordan Rose 1063fa0734ecSArgyrios Kyrtzidis // If we get here, we have no way of comparing the regions. 1064fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1065fa0734ecSArgyrios Kyrtzidis } 1066fa0734ecSArgyrios Kyrtzidis } 1067fa0734ecSArgyrios Kyrtzidis } 1068fa0734ecSArgyrios Kyrtzidis 106949b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state, 10709cbfdde2SValeriy Savchenko BinaryOperator::Opcode op, Loc lhs, 10719cbfdde2SValeriy Savchenko NonLoc rhs, QualType resultTy) { 107264c01f7bSDevin Coughlin if (op >= BO_PtrMemD && op <= BO_PtrMemI) { 107364c01f7bSDevin Coughlin if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) { 107464c01f7bSDevin Coughlin if (PTMSV->isNullMemberPointer()) 107564c01f7bSDevin Coughlin return UndefinedVal(); 10769cbfdde2SValeriy Savchenko 10779cbfdde2SValeriy Savchenko auto getFieldLValue = [&](const auto *FD) -> SVal { 107864c01f7bSDevin Coughlin SVal Result = lhs; 107964c01f7bSDevin Coughlin 108064c01f7bSDevin Coughlin for (const auto &I : *PTMSV) 108164c01f7bSDevin Coughlin Result = StateMgr.getStoreManager().evalDerivedToBase( 108264c01f7bSDevin Coughlin Result, I->getType(), I->isVirtual()); 10839cbfdde2SValeriy Savchenko 108464c01f7bSDevin Coughlin return state->getLValue(FD, Result); 10859cbfdde2SValeriy Savchenko }; 10869cbfdde2SValeriy Savchenko 10879cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) { 10889cbfdde2SValeriy Savchenko return getFieldLValue(FD); 10899cbfdde2SValeriy Savchenko } 10909cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) { 10919cbfdde2SValeriy Savchenko return getFieldLValue(FD); 109264c01f7bSDevin Coughlin } 109364c01f7bSDevin Coughlin } 109464c01f7bSDevin Coughlin 109564c01f7bSDevin Coughlin return rhs; 109664c01f7bSDevin Coughlin } 109764c01f7bSDevin Coughlin 1098686df322SJordan Rose assert(!BinaryOperator::isComparisonOp(op) && 1099686df322SJordan Rose "arguments to comparison ops must be of the same type"); 1100fa0734ecSArgyrios Kyrtzidis 1101fa0734ecSArgyrios Kyrtzidis // Special case: rhs is a zero constant. 1102fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant()) 1103fa0734ecSArgyrios Kyrtzidis return lhs; 1104fa0734ecSArgyrios Kyrtzidis 110521524676SGabor Horvath // Perserve the null pointer so that it can be found by the DerefChecker. 110621524676SGabor Horvath if (lhs.isZeroConstant()) 110721524676SGabor Horvath return lhs; 110821524676SGabor Horvath 1109fa0734ecSArgyrios Kyrtzidis // We are dealing with pointer arithmetic. 1110fa0734ecSArgyrios Kyrtzidis 1111fa0734ecSArgyrios Kyrtzidis // Handle pointer arithmetic on constant values. 111205785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) { 111305785d16SDavid Blaikie if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) { 1114fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &leftI = lhsInt->getValue(); 1115fa0734ecSArgyrios Kyrtzidis assert(leftI.isUnsigned()); 1116fa0734ecSArgyrios Kyrtzidis llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true); 1117fa0734ecSArgyrios Kyrtzidis 1118fa0734ecSArgyrios Kyrtzidis // Convert the bitwidth of rightI. This should deal with overflow 1119fa0734ecSArgyrios Kyrtzidis // since we are dealing with concrete values. 1120fa0734ecSArgyrios Kyrtzidis rightI = rightI.extOrTrunc(leftI.getBitWidth()); 1121fa0734ecSArgyrios Kyrtzidis 1122fa0734ecSArgyrios Kyrtzidis // Offset the increment by the pointer size. 1123fa0734ecSArgyrios Kyrtzidis llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true); 112421524676SGabor Horvath QualType pointeeType = resultTy->getPointeeType(); 112521524676SGabor Horvath Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity(); 1126fa0734ecSArgyrios Kyrtzidis rightI *= Multiplicand; 1127fa0734ecSArgyrios Kyrtzidis 1128fa0734ecSArgyrios Kyrtzidis // Compute the adjusted pointer. 1129fa0734ecSArgyrios Kyrtzidis switch (op) { 1130fa0734ecSArgyrios Kyrtzidis case BO_Add: 1131fa0734ecSArgyrios Kyrtzidis rightI = leftI + rightI; 1132fa0734ecSArgyrios Kyrtzidis break; 1133fa0734ecSArgyrios Kyrtzidis case BO_Sub: 1134fa0734ecSArgyrios Kyrtzidis rightI = leftI - rightI; 1135fa0734ecSArgyrios Kyrtzidis break; 1136fa0734ecSArgyrios Kyrtzidis default: 1137fa0734ecSArgyrios Kyrtzidis llvm_unreachable("Invalid pointer arithmetic operation"); 1138fa0734ecSArgyrios Kyrtzidis } 1139fa0734ecSArgyrios Kyrtzidis return loc::ConcreteInt(getBasicValueFactory().getValue(rightI)); 1140fa0734ecSArgyrios Kyrtzidis } 1141fa0734ecSArgyrios Kyrtzidis } 1142fa0734ecSArgyrios Kyrtzidis 1143fa0734ecSArgyrios Kyrtzidis // Handle cases where 'lhs' is a region. 1144fa0734ecSArgyrios Kyrtzidis if (const MemRegion *region = lhs.getAsRegion()) { 11452fdacbc5SDavid Blaikie rhs = convertToArrayIndex(rhs).castAs<NonLoc>(); 1146fa0734ecSArgyrios Kyrtzidis SVal index = UnknownVal(); 11476dd11048SArtem Dergachev const SubRegion *superR = nullptr; 11487333a9eaSArtem Dergachev // We need to know the type of the pointer in order to add an integer to it. 11497333a9eaSArtem Dergachev // Depending on the type, different amount of bytes is added. 1150fa0734ecSArgyrios Kyrtzidis QualType elementType; 1151fa0734ecSArgyrios Kyrtzidis 1152fa0734ecSArgyrios Kyrtzidis if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) { 115357a4a152STed Kremenek assert(op == BO_Add || op == BO_Sub); 115457a4a152STed Kremenek index = evalBinOpNN(state, op, elemReg->getIndex(), rhs, 1155fa0734ecSArgyrios Kyrtzidis getArrayIndexType()); 11566dd11048SArtem Dergachev superR = cast<SubRegion>(elemReg->getSuperRegion()); 1157fa0734ecSArgyrios Kyrtzidis elementType = elemReg->getElementType(); 1158fa0734ecSArgyrios Kyrtzidis } 1159fa0734ecSArgyrios Kyrtzidis else if (isa<SubRegion>(region)) { 1160c4b28a8fSGabor Horvath assert(op == BO_Add || op == BO_Sub); 1161c4b28a8fSGabor Horvath index = (op == BO_Add) ? rhs : evalMinus(rhs); 11626dd11048SArtem Dergachev superR = cast<SubRegion>(region); 11637333a9eaSArtem Dergachev // TODO: Is this actually reliable? Maybe improving our MemRegion 11647333a9eaSArtem Dergachev // hierarchy to provide typed regions for all non-void pointers would be 11657333a9eaSArtem Dergachev // better. For instance, we cannot extend this towards LocAsInteger 11667333a9eaSArtem Dergachev // operations, where result type of the expression is integer. 1167d1a08b6eSJordan Rose if (resultTy->isAnyPointerType()) 1168d1a08b6eSJordan Rose elementType = resultTy->getPointeeType(); 1169fa0734ecSArgyrios Kyrtzidis } 1170fa0734ecSArgyrios Kyrtzidis 1171df1bb8a6SArtem Dergachev // Represent arithmetic on void pointers as arithmetic on char pointers. 1172df1bb8a6SArtem Dergachev // It is fine when a TypedValueRegion of char value type represents 1173df1bb8a6SArtem Dergachev // a void pointer. Note that arithmetic on void pointers is a GCC extension. 1174df1bb8a6SArtem Dergachev if (elementType->isVoidType()) 1175df1bb8a6SArtem Dergachev elementType = getContext().CharTy; 1176df1bb8a6SArtem Dergachev 117705785d16SDavid Blaikie if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) { 1178fa0734ecSArgyrios Kyrtzidis return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV, 1179fa0734ecSArgyrios Kyrtzidis superR, getContext())); 1180fa0734ecSArgyrios Kyrtzidis } 1181fa0734ecSArgyrios Kyrtzidis } 1182fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1183fa0734ecSArgyrios Kyrtzidis } 1184fa0734ecSArgyrios Kyrtzidis 118549b1e38eSTed Kremenek const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state, 1186fa0734ecSArgyrios Kyrtzidis SVal V) { 11879ff67a9dSGeorge Karpenkov V = simplifySVal(state, V); 1188fa0734ecSArgyrios Kyrtzidis if (V.isUnknownOrUndef()) 11890dbb783cSCraig Topper return nullptr; 1190fa0734ecSArgyrios Kyrtzidis 119105785d16SDavid Blaikie if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>()) 1192fa0734ecSArgyrios Kyrtzidis return &X->getValue(); 1193fa0734ecSArgyrios Kyrtzidis 119405785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>()) 1195fa0734ecSArgyrios Kyrtzidis return &X->getValue(); 1196fa0734ecSArgyrios Kyrtzidis 1197fa0734ecSArgyrios Kyrtzidis if (SymbolRef Sym = V.getAsSymbol()) 1198244e1d7dSTed Kremenek return state->getConstraintManager().getSymVal(state, Sym); 1199fa0734ecSArgyrios Kyrtzidis 12000dbb783cSCraig Topper return nullptr; 1201fa0734ecSArgyrios Kyrtzidis } 120212294f8dSArtem Dergachev 1203978431e8SGabor Marton SVal SimpleSValBuilder::simplifyUntilFixpoint(ProgramStateRef State, SVal Val) { 1204978431e8SGabor Marton SVal SimplifiedVal = simplifySValOnce(State, Val); 1205978431e8SGabor Marton while (SimplifiedVal != Val) { 1206978431e8SGabor Marton Val = SimplifiedVal; 1207978431e8SGabor Marton SimplifiedVal = simplifySValOnce(State, Val); 1208978431e8SGabor Marton } 1209978431e8SGabor Marton return SimplifiedVal; 1210978431e8SGabor Marton } 1211978431e8SGabor Marton 121212294f8dSArtem Dergachev SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { 1213978431e8SGabor Marton return simplifyUntilFixpoint(State, V); 1214978431e8SGabor Marton } 1215978431e8SGabor Marton 1216978431e8SGabor Marton SVal SimpleSValBuilder::simplifySValOnce(ProgramStateRef State, SVal V) { 121712294f8dSArtem Dergachev // For now, this function tries to constant-fold symbols inside a 121812294f8dSArtem Dergachev // nonloc::SymbolVal, and does nothing else. More simplifications should 121912294f8dSArtem Dergachev // be possible, such as constant-folding an index in an ElementRegion. 122012294f8dSArtem Dergachev 122112294f8dSArtem Dergachev class Simplifier : public FullSValVisitor<Simplifier, SVal> { 122212294f8dSArtem Dergachev ProgramStateRef State; 122312294f8dSArtem Dergachev SValBuilder &SVB; 122412294f8dSArtem Dergachev 122522746d7dSArtem Dergachev // Cache results for the lifetime of the Simplifier. Results change every 122622746d7dSArtem Dergachev // time new constraints are added to the program state, which is the whole 122722746d7dSArtem Dergachev // point of simplifying, and for that very reason it's pointless to maintain 122822746d7dSArtem Dergachev // the same cache for the duration of the whole analysis. 122922746d7dSArtem Dergachev llvm::DenseMap<SymbolRef, SVal> Cached; 123022746d7dSArtem Dergachev 123116a1f64cSArtem Dergachev static bool isUnchanged(SymbolRef Sym, SVal Val) { 123216a1f64cSArtem Dergachev return Sym == Val.getAsSymbol(); 123316a1f64cSArtem Dergachev } 123416a1f64cSArtem Dergachev 12359fe9a95fSArtem Dergachev SVal cache(SymbolRef Sym, SVal V) { 12369fe9a95fSArtem Dergachev Cached[Sym] = V; 12379fe9a95fSArtem Dergachev return V; 12389fe9a95fSArtem Dergachev } 12399fe9a95fSArtem Dergachev 12409fe9a95fSArtem Dergachev SVal skip(SymbolRef Sym) { 12419fe9a95fSArtem Dergachev return cache(Sym, SVB.makeSymbolVal(Sym)); 12429fe9a95fSArtem Dergachev } 12439fe9a95fSArtem Dergachev 12440a17896fSGabor Marton // Return the known const value for the Sym if available, or return Undef 12450a17896fSGabor Marton // otherwise. 12460a17896fSGabor Marton SVal getConst(SymbolRef Sym) { 12470a17896fSGabor Marton const llvm::APSInt *Const = 12480a17896fSGabor Marton State->getConstraintManager().getSymVal(State, Sym); 12490a17896fSGabor Marton if (Const) 12500a17896fSGabor Marton return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const) 12510a17896fSGabor Marton : (SVal)SVB.makeIntVal(*Const); 12520a17896fSGabor Marton return UndefinedVal(); 12530a17896fSGabor Marton } 12540a17896fSGabor Marton 12550a17896fSGabor Marton SVal getConstOrVisit(SymbolRef Sym) { 12560a17896fSGabor Marton const SVal Ret = getConst(Sym); 12570a17896fSGabor Marton if (Ret.isUndef()) 12580a17896fSGabor Marton return Visit(Sym); 12590a17896fSGabor Marton return Ret; 12600a17896fSGabor Marton } 12610a17896fSGabor Marton 126212294f8dSArtem Dergachev public: 126312294f8dSArtem Dergachev Simplifier(ProgramStateRef State) 126412294f8dSArtem Dergachev : State(State), SVB(State->getStateManager().getSValBuilder()) {} 126512294f8dSArtem Dergachev 126612294f8dSArtem Dergachev SVal VisitSymbolData(const SymbolData *S) { 12679fe9a95fSArtem Dergachev // No cache here. 126812294f8dSArtem Dergachev if (const llvm::APSInt *I = 1269d1163790SArtem Dergachev SVB.getKnownValue(State, SVB.makeSymbolVal(S))) 127012294f8dSArtem Dergachev return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I) 127112294f8dSArtem Dergachev : (SVal)SVB.makeIntVal(*I); 127216a1f64cSArtem Dergachev return SVB.makeSymbolVal(S); 127312294f8dSArtem Dergachev } 127412294f8dSArtem Dergachev 12750a17896fSGabor Marton // TODO: Support SymbolCast. 127612294f8dSArtem Dergachev 127712294f8dSArtem Dergachev SVal VisitSymIntExpr(const SymIntExpr *S) { 127822746d7dSArtem Dergachev auto I = Cached.find(S); 127922746d7dSArtem Dergachev if (I != Cached.end()) 128022746d7dSArtem Dergachev return I->second; 128122746d7dSArtem Dergachev 12820a17896fSGabor Marton SVal LHS = getConstOrVisit(S->getLHS()); 12839fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS)) 12849fe9a95fSArtem Dergachev return skip(S); 12859fe9a95fSArtem Dergachev 128612294f8dSArtem Dergachev SVal RHS; 128712294f8dSArtem Dergachev // By looking at the APSInt in the right-hand side of S, we cannot 128812294f8dSArtem Dergachev // figure out if it should be treated as a Loc or as a NonLoc. 128912294f8dSArtem Dergachev // So make our guess by recalling that we cannot multiply pointers 129012294f8dSArtem Dergachev // or compare a pointer to an integer. 129112294f8dSArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) && 129212294f8dSArtem Dergachev BinaryOperator::isComparisonOp(S->getOpcode())) { 129312294f8dSArtem Dergachev // The usual conversion of $sym to &SymRegion{$sym}, as they have 129412294f8dSArtem Dergachev // the same meaning for Loc-type symbols, but the latter form 129512294f8dSArtem Dergachev // is preferred in SVal computations for being Loc itself. 129612294f8dSArtem Dergachev if (SymbolRef Sym = LHS.getAsSymbol()) { 129712294f8dSArtem Dergachev assert(Loc::isLocType(Sym->getType())); 129812294f8dSArtem Dergachev LHS = SVB.makeLoc(Sym); 129912294f8dSArtem Dergachev } 130012294f8dSArtem Dergachev RHS = SVB.makeIntLocVal(S->getRHS()); 130112294f8dSArtem Dergachev } else { 130212294f8dSArtem Dergachev RHS = SVB.makeIntVal(S->getRHS()); 130312294f8dSArtem Dergachev } 130422746d7dSArtem Dergachev 13059fe9a95fSArtem Dergachev return cache( 13069fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 130712294f8dSArtem Dergachev } 130812294f8dSArtem Dergachev 1309ffc32efdSGabor Marton SVal VisitIntSymExpr(const IntSymExpr *S) { 1310ffc32efdSGabor Marton auto I = Cached.find(S); 1311ffc32efdSGabor Marton if (I != Cached.end()) 1312ffc32efdSGabor Marton return I->second; 1313ffc32efdSGabor Marton 13140a17896fSGabor Marton SVal RHS = getConstOrVisit(S->getRHS()); 1315ffc32efdSGabor Marton if (isUnchanged(S->getRHS(), RHS)) 1316ffc32efdSGabor Marton return skip(S); 13170a17896fSGabor Marton 1318ffc32efdSGabor Marton SVal LHS = SVB.makeIntVal(S->getLHS()); 1319ffc32efdSGabor Marton return cache( 1320ffc32efdSGabor Marton S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 1321ffc32efdSGabor Marton } 1322ffc32efdSGabor Marton 132312294f8dSArtem Dergachev SVal VisitSymSymExpr(const SymSymExpr *S) { 132422746d7dSArtem Dergachev auto I = Cached.find(S); 132522746d7dSArtem Dergachev if (I != Cached.end()) 132622746d7dSArtem Dergachev return I->second; 132722746d7dSArtem Dergachev 132805220a90SArtem Dergachev // For now don't try to simplify mixed Loc/NonLoc expressions 132905220a90SArtem Dergachev // because they often appear from LocAsInteger operations 133005220a90SArtem Dergachev // and we don't know how to combine a LocAsInteger 133105220a90SArtem Dergachev // with a concrete value. 133205220a90SArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) != 13339fe9a95fSArtem Dergachev Loc::isLocType(S->getRHS()->getType())) 13349fe9a95fSArtem Dergachev return skip(S); 133505220a90SArtem Dergachev 13360a17896fSGabor Marton SVal LHS = getConstOrVisit(S->getLHS()); 13370a17896fSGabor Marton SVal RHS = getConstOrVisit(S->getRHS()); 13380a17896fSGabor Marton 13399fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS)) 13409fe9a95fSArtem Dergachev return skip(S); 13419fe9a95fSArtem Dergachev 13429fe9a95fSArtem Dergachev return cache( 13439fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 134412294f8dSArtem Dergachev } 134512294f8dSArtem Dergachev 134612294f8dSArtem Dergachev SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); } 134712294f8dSArtem Dergachev 134812294f8dSArtem Dergachev SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); } 134912294f8dSArtem Dergachev 135012294f8dSArtem Dergachev SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) { 135112294f8dSArtem Dergachev // Simplification is much more costly than computing complexity. 135212294f8dSArtem Dergachev // For high complexity, it may be not worth it. 135312294f8dSArtem Dergachev return Visit(V.getSymbol()); 135412294f8dSArtem Dergachev } 135512294f8dSArtem Dergachev 135612294f8dSArtem Dergachev SVal VisitSVal(SVal V) { return V; } 135712294f8dSArtem Dergachev }; 135812294f8dSArtem Dergachev 135916a1f64cSArtem Dergachev // A crude way of preventing this function from calling itself from evalBinOp. 136016a1f64cSArtem Dergachev static bool isReentering = false; 136116a1f64cSArtem Dergachev if (isReentering) 136216a1f64cSArtem Dergachev return V; 136316a1f64cSArtem Dergachev 136416a1f64cSArtem Dergachev isReentering = true; 136516a1f64cSArtem Dergachev SVal SimplifiedV = Simplifier(State).Visit(V); 136616a1f64cSArtem Dergachev isReentering = false; 136716a1f64cSArtem Dergachev 136816a1f64cSArtem Dergachev return SimplifiedV; 136912294f8dSArtem Dergachev } 1370