1fa0734ecSArgyrios Kyrtzidis // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2fa0734ecSArgyrios Kyrtzidis //
3fa0734ecSArgyrios Kyrtzidis //                     The LLVM Compiler Infrastructure
4fa0734ecSArgyrios Kyrtzidis //
5fa0734ecSArgyrios Kyrtzidis // This file is distributed under the University of Illinois Open Source
6fa0734ecSArgyrios Kyrtzidis // License. See LICENSE.TXT for details.
7fa0734ecSArgyrios Kyrtzidis //
8fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
9fa0734ecSArgyrios Kyrtzidis //
10fa0734ecSArgyrios Kyrtzidis //  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
11fa0734ecSArgyrios Kyrtzidis //
12fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
13fa0734ecSArgyrios Kyrtzidis 
14f8cbac4bSTed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
15*2bbccca9SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
163a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
17001fd5b4STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
18*2bbccca9SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
1912294f8dSArtem Dergachev #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
20fa0734ecSArgyrios Kyrtzidis 
21fa0734ecSArgyrios Kyrtzidis using namespace clang;
22fa0734ecSArgyrios Kyrtzidis using namespace ento;
23fa0734ecSArgyrios Kyrtzidis 
24fa0734ecSArgyrios Kyrtzidis namespace {
25fa0734ecSArgyrios Kyrtzidis class SimpleSValBuilder : public SValBuilder {
26fa0734ecSArgyrios Kyrtzidis protected:
27fb6b25b5SCraig Topper   SVal dispatchCast(SVal val, QualType castTy) override;
28fb6b25b5SCraig Topper   SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
29fb6b25b5SCraig Topper   SVal evalCastFromLoc(Loc val, QualType castTy) override;
30fa0734ecSArgyrios Kyrtzidis 
31fa0734ecSArgyrios Kyrtzidis public:
32fa0734ecSArgyrios Kyrtzidis   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
33001fd5b4STed Kremenek                     ProgramStateManager &stateMgr)
34fa0734ecSArgyrios Kyrtzidis                     : SValBuilder(alloc, context, stateMgr) {}
35637d1e66SAngel Garcia Gomez   ~SimpleSValBuilder() override {}
36fa0734ecSArgyrios Kyrtzidis 
37fb6b25b5SCraig Topper   SVal evalMinus(NonLoc val) override;
38fb6b25b5SCraig Topper   SVal evalComplement(NonLoc val) override;
39fb6b25b5SCraig Topper   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
40fb6b25b5SCraig Topper                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
41fb6b25b5SCraig Topper   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
42fb6b25b5SCraig Topper                    Loc lhs, Loc rhs, QualType resultTy) override;
43fb6b25b5SCraig Topper   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
44fb6b25b5SCraig Topper                    Loc lhs, NonLoc rhs, QualType resultTy) override;
45fa0734ecSArgyrios Kyrtzidis 
46fa0734ecSArgyrios Kyrtzidis   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
47fa0734ecSArgyrios Kyrtzidis   ///  (integer) value, that value is returned. Otherwise, returns NULL.
48fb6b25b5SCraig Topper   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
49fa0734ecSArgyrios Kyrtzidis 
5012294f8dSArtem Dergachev   /// Recursively descends into symbolic expressions and replaces symbols
5112294f8dSArtem Dergachev   /// with their known values (in the sense of the getKnownValue() method).
5212294f8dSArtem Dergachev   SVal simplifySVal(ProgramStateRef State, SVal V) override;
5312294f8dSArtem Dergachev 
54fa0734ecSArgyrios Kyrtzidis   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
55fa0734ecSArgyrios Kyrtzidis                      const llvm::APSInt &RHS, QualType resultTy);
56fa0734ecSArgyrios Kyrtzidis };
57fa0734ecSArgyrios Kyrtzidis } // end anonymous namespace
58fa0734ecSArgyrios Kyrtzidis 
59fa0734ecSArgyrios Kyrtzidis SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
60fa0734ecSArgyrios Kyrtzidis                                            ASTContext &context,
61001fd5b4STed Kremenek                                            ProgramStateManager &stateMgr) {
62fa0734ecSArgyrios Kyrtzidis   return new SimpleSValBuilder(alloc, context, stateMgr);
63fa0734ecSArgyrios Kyrtzidis }
64fa0734ecSArgyrios Kyrtzidis 
65fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
66fa0734ecSArgyrios Kyrtzidis // Transfer function for Casts.
67fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
68fa0734ecSArgyrios Kyrtzidis 
69c95a6c4cSAnna Zaks SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
702fdacbc5SDavid Blaikie   assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
712fdacbc5SDavid Blaikie   return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
722fdacbc5SDavid Blaikie                            : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
73c25efcccSAnna Zaks }
74c25efcccSAnna Zaks 
755ad574c0SZhanyong Wan SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
7685a203ebSZhanyong Wan   bool isLocType = Loc::isLocType(castTy);
7764c01f7bSDevin Coughlin   if (val.getAs<nonloc::PointerToMember>())
7864c01f7bSDevin Coughlin     return val;
7964c01f7bSDevin Coughlin 
8005785d16SDavid Blaikie   if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
81fa0734ecSArgyrios Kyrtzidis     if (isLocType)
82fa0734ecSArgyrios Kyrtzidis       return LI->getLoc();
83fa0734ecSArgyrios Kyrtzidis     // FIXME: Correctly support promotions/truncations.
8459d10a4cSAlexander Shaposhnikov     unsigned castSize = Context.getIntWidth(castTy);
85fa0734ecSArgyrios Kyrtzidis     if (castSize == LI->getNumBits())
86fa0734ecSArgyrios Kyrtzidis       return val;
87fa0734ecSArgyrios Kyrtzidis     return makeLocAsInteger(LI->getLoc(), castSize);
88fa0734ecSArgyrios Kyrtzidis   }
89fa0734ecSArgyrios Kyrtzidis 
90fa0734ecSArgyrios Kyrtzidis   if (const SymExpr *se = val.getAsSymbolicExpression()) {
91a808e165STed Kremenek     QualType T = Context.getCanonicalType(se->getType());
926af472aaSAnna Zaks     // If types are the same or both are integers, ignore the cast.
93fa0734ecSArgyrios Kyrtzidis     // FIXME: Remove this hack when we support symbolic truncation/extension.
94fa0734ecSArgyrios Kyrtzidis     // HACK: If both castTy and T are integers, ignore the cast.  This is
95fa0734ecSArgyrios Kyrtzidis     // not a permanent solution.  Eventually we want to precisely handle
96fa0734ecSArgyrios Kyrtzidis     // extension/truncation of symbolic integers.  This prevents us from losing
97fa0734ecSArgyrios Kyrtzidis     // precision when we assign 'x = y' and 'y' is symbolic and x and y are
98fa0734ecSArgyrios Kyrtzidis     // different integer types.
996af472aaSAnna Zaks    if (haveSameType(T, castTy))
100fa0734ecSArgyrios Kyrtzidis       return val;
101fa0734ecSArgyrios Kyrtzidis 
102c25efcccSAnna Zaks     if (!isLocType)
103c25efcccSAnna Zaks       return makeNonLoc(se, T, castTy);
104fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
105fa0734ecSArgyrios Kyrtzidis   }
106fa0734ecSArgyrios Kyrtzidis 
107d4733638SAlp Toker   // If value is a non-integer constant, produce unknown.
1082fdacbc5SDavid Blaikie   if (!val.getAs<nonloc::ConcreteInt>())
109fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
110fa0734ecSArgyrios Kyrtzidis 
1112317f30fSTed Kremenek   // Handle casts to a boolean type.
1122317f30fSTed Kremenek   if (castTy->isBooleanType()) {
1132fdacbc5SDavid Blaikie     bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
1142317f30fSTed Kremenek     return makeTruthVal(b, castTy);
1152317f30fSTed Kremenek   }
1162317f30fSTed Kremenek 
117394256ccSAnna Zaks   // Only handle casts from integers to integers - if val is an integer constant
118d4733638SAlp Toker   // being cast to a non-integer type, produce unknown.
11961e221f6SJordan Rose   if (!isLocType && !castTy->isIntegralOrEnumerationType())
120fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
121fa0734ecSArgyrios Kyrtzidis 
1222fdacbc5SDavid Blaikie   llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
1237e3c3ea3SJordy Rose   BasicVals.getAPSIntType(castTy).apply(i);
124fa0734ecSArgyrios Kyrtzidis 
125fa0734ecSArgyrios Kyrtzidis   if (isLocType)
126fa0734ecSArgyrios Kyrtzidis     return makeIntLocVal(i);
127fa0734ecSArgyrios Kyrtzidis   else
128fa0734ecSArgyrios Kyrtzidis     return makeIntVal(i);
129fa0734ecSArgyrios Kyrtzidis }
130fa0734ecSArgyrios Kyrtzidis 
1315ad574c0SZhanyong Wan SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
132fa0734ecSArgyrios Kyrtzidis 
133fa0734ecSArgyrios Kyrtzidis   // Casts from pointers -> pointers, just return the lval.
134fa0734ecSArgyrios Kyrtzidis   //
135fa0734ecSArgyrios Kyrtzidis   // Casts from pointers -> references, just return the lval.  These
136fa0734ecSArgyrios Kyrtzidis   //   can be introduced by the frontend for corner cases, e.g
137fa0734ecSArgyrios Kyrtzidis   //   casting from va_list* to __builtin_va_list&.
138fa0734ecSArgyrios Kyrtzidis   //
13985a203ebSZhanyong Wan   if (Loc::isLocType(castTy) || castTy->isReferenceType())
140fa0734ecSArgyrios Kyrtzidis     return val;
141fa0734ecSArgyrios Kyrtzidis 
142fa0734ecSArgyrios Kyrtzidis   // FIXME: Handle transparent unions where a value can be "transparently"
143fa0734ecSArgyrios Kyrtzidis   //  lifted into a union type.
144fa0734ecSArgyrios Kyrtzidis   if (castTy->isUnionType())
145fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
146fa0734ecSArgyrios Kyrtzidis 
147acd080b9SJordan Rose   // Casting a Loc to a bool will almost always be true,
148acd080b9SJordan Rose   // unless this is a weak function or a symbolic region.
149acd080b9SJordan Rose   if (castTy->isBooleanType()) {
150acd080b9SJordan Rose     switch (val.getSubKind()) {
15173f018e3SArtem Dergachev       case loc::MemRegionValKind: {
152acd080b9SJordan Rose         const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
15373f018e3SArtem Dergachev         if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
154acd080b9SJordan Rose           if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
155acd080b9SJordan Rose             if (FD->isWeak())
156acd080b9SJordan Rose               // FIXME: Currently we are using an extent symbol here,
157acd080b9SJordan Rose               // because there are no generic region address metadata
158acd080b9SJordan Rose               // symbols to use, only content metadata.
159acd080b9SJordan Rose               return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
160acd080b9SJordan Rose 
161acd080b9SJordan Rose         if (const SymbolicRegion *SymR = R->getSymbolicBase())
162acd080b9SJordan Rose           return nonloc::SymbolVal(SymR->getSymbol());
163acd080b9SJordan Rose 
164acd080b9SJordan Rose         // FALL-THROUGH
165a65d5785SGalina Kistanova         LLVM_FALLTHROUGH;
166acd080b9SJordan Rose       }
167acd080b9SJordan Rose 
168acd080b9SJordan Rose       case loc::GotoLabelKind:
169d4733638SAlp Toker         // Labels and non-symbolic memory regions are always true.
170acd080b9SJordan Rose         return makeTruthVal(true, castTy);
171acd080b9SJordan Rose     }
172acd080b9SJordan Rose   }
173acd080b9SJordan Rose 
17461e221f6SJordan Rose   if (castTy->isIntegralOrEnumerationType()) {
17559d10a4cSAlexander Shaposhnikov     unsigned BitWidth = Context.getIntWidth(castTy);
176fa0734ecSArgyrios Kyrtzidis 
1772fdacbc5SDavid Blaikie     if (!val.getAs<loc::ConcreteInt>())
178fa0734ecSArgyrios Kyrtzidis       return makeLocAsInteger(val, BitWidth);
179fa0734ecSArgyrios Kyrtzidis 
1802fdacbc5SDavid Blaikie     llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
1817e3c3ea3SJordy Rose     BasicVals.getAPSIntType(castTy).apply(i);
182fa0734ecSArgyrios Kyrtzidis     return makeIntVal(i);
183fa0734ecSArgyrios Kyrtzidis   }
184fa0734ecSArgyrios Kyrtzidis 
185fa0734ecSArgyrios Kyrtzidis   // All other cases: return 'UnknownVal'.  This includes casting pointers
186fa0734ecSArgyrios Kyrtzidis   // to floats, which is probably badness it itself, but this is a good
187fa0734ecSArgyrios Kyrtzidis   // intermediate solution until we do something better.
188fa0734ecSArgyrios Kyrtzidis   return UnknownVal();
189fa0734ecSArgyrios Kyrtzidis }
190fa0734ecSArgyrios Kyrtzidis 
191fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
192fa0734ecSArgyrios Kyrtzidis // Transfer function for unary operators.
193fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
194fa0734ecSArgyrios Kyrtzidis 
195fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalMinus(NonLoc val) {
196fa0734ecSArgyrios Kyrtzidis   switch (val.getSubKind()) {
197fa0734ecSArgyrios Kyrtzidis   case nonloc::ConcreteIntKind:
1982fdacbc5SDavid Blaikie     return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
199fa0734ecSArgyrios Kyrtzidis   default:
200fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
201fa0734ecSArgyrios Kyrtzidis   }
202fa0734ecSArgyrios Kyrtzidis }
203fa0734ecSArgyrios Kyrtzidis 
204fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalComplement(NonLoc X) {
205fa0734ecSArgyrios Kyrtzidis   switch (X.getSubKind()) {
206fa0734ecSArgyrios Kyrtzidis   case nonloc::ConcreteIntKind:
2072fdacbc5SDavid Blaikie     return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
208fa0734ecSArgyrios Kyrtzidis   default:
209fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
210fa0734ecSArgyrios Kyrtzidis   }
211fa0734ecSArgyrios Kyrtzidis }
212fa0734ecSArgyrios Kyrtzidis 
213fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
214fa0734ecSArgyrios Kyrtzidis // Transfer function for binary operators.
215fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
216fa0734ecSArgyrios Kyrtzidis 
217fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
218fa0734ecSArgyrios Kyrtzidis                                     BinaryOperator::Opcode op,
219fa0734ecSArgyrios Kyrtzidis                                     const llvm::APSInt &RHS,
220fa0734ecSArgyrios Kyrtzidis                                     QualType resultTy) {
221fa0734ecSArgyrios Kyrtzidis   bool isIdempotent = false;
222fa0734ecSArgyrios Kyrtzidis 
223fa0734ecSArgyrios Kyrtzidis   // Check for a few special cases with known reductions first.
224fa0734ecSArgyrios Kyrtzidis   switch (op) {
225fa0734ecSArgyrios Kyrtzidis   default:
226fa0734ecSArgyrios Kyrtzidis     // We can't reduce this case; just treat it normally.
227fa0734ecSArgyrios Kyrtzidis     break;
228fa0734ecSArgyrios Kyrtzidis   case BO_Mul:
229fa0734ecSArgyrios Kyrtzidis     // a*0 and a*1
230fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
231fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
232fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
233fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
234fa0734ecSArgyrios Kyrtzidis     break;
235fa0734ecSArgyrios Kyrtzidis   case BO_Div:
236fa0734ecSArgyrios Kyrtzidis     // a/0 and a/1
237fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
238fa0734ecSArgyrios Kyrtzidis       // This is also handled elsewhere.
239fa0734ecSArgyrios Kyrtzidis       return UndefinedVal();
240fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
241fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
242fa0734ecSArgyrios Kyrtzidis     break;
243fa0734ecSArgyrios Kyrtzidis   case BO_Rem:
244fa0734ecSArgyrios Kyrtzidis     // a%0 and a%1
245fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
246fa0734ecSArgyrios Kyrtzidis       // This is also handled elsewhere.
247fa0734ecSArgyrios Kyrtzidis       return UndefinedVal();
248fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
249fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
250fa0734ecSArgyrios Kyrtzidis     break;
251fa0734ecSArgyrios Kyrtzidis   case BO_Add:
252fa0734ecSArgyrios Kyrtzidis   case BO_Sub:
253fa0734ecSArgyrios Kyrtzidis   case BO_Shl:
254fa0734ecSArgyrios Kyrtzidis   case BO_Shr:
255fa0734ecSArgyrios Kyrtzidis   case BO_Xor:
256fa0734ecSArgyrios Kyrtzidis     // a+0, a-0, a<<0, a>>0, a^0
257fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
258fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
259fa0734ecSArgyrios Kyrtzidis     break;
260fa0734ecSArgyrios Kyrtzidis   case BO_And:
261fa0734ecSArgyrios Kyrtzidis     // a&0 and a&(~0)
262fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
263fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
264fa0734ecSArgyrios Kyrtzidis     else if (RHS.isAllOnesValue())
265fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
266fa0734ecSArgyrios Kyrtzidis     break;
267fa0734ecSArgyrios Kyrtzidis   case BO_Or:
268fa0734ecSArgyrios Kyrtzidis     // a|0 and a|(~0)
269fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
270fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
271fa0734ecSArgyrios Kyrtzidis     else if (RHS.isAllOnesValue()) {
272fa0734ecSArgyrios Kyrtzidis       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
273fa0734ecSArgyrios Kyrtzidis       return nonloc::ConcreteInt(Result);
274fa0734ecSArgyrios Kyrtzidis     }
275fa0734ecSArgyrios Kyrtzidis     break;
276fa0734ecSArgyrios Kyrtzidis   }
277fa0734ecSArgyrios Kyrtzidis 
278fa0734ecSArgyrios Kyrtzidis   // Idempotent ops (like a*1) can still change the type of an expression.
2795ad574c0SZhanyong Wan   // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
2805ad574c0SZhanyong Wan   // dirty work.
281d066f79cSAnna Zaks   if (isIdempotent)
282a636fbe7SAnna Zaks       return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
283fa0734ecSArgyrios Kyrtzidis 
284fa0734ecSArgyrios Kyrtzidis   // If we reach this point, the expression cannot be simplified.
28554569448SJordy Rose   // Make a SymbolVal for the entire expression, after converting the RHS.
28654569448SJordy Rose   const llvm::APSInt *ConvertedRHS = &RHS;
28754569448SJordy Rose   if (BinaryOperator::isComparisonOp(op)) {
28854569448SJordy Rose     // We're looking for a type big enough to compare the symbolic value
28954569448SJordy Rose     // with the given constant.
29054569448SJordy Rose     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
29154569448SJordy Rose     ASTContext &Ctx = getContext();
292a808e165STed Kremenek     QualType SymbolType = LHS->getType();
29354569448SJordy Rose     uint64_t ValWidth = RHS.getBitWidth();
29454569448SJordy Rose     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
29554569448SJordy Rose 
29654569448SJordy Rose     if (ValWidth < TypeWidth) {
29754569448SJordy Rose       // If the value is too small, extend it.
29854569448SJordy Rose       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
29954569448SJordy Rose     } else if (ValWidth == TypeWidth) {
30054569448SJordy Rose       // If the value is signed but the symbol is unsigned, do the comparison
30154569448SJordy Rose       // in unsigned space. [C99 6.3.1.8]
30254569448SJordy Rose       // (For the opposite case, the value is already unsigned.)
30354569448SJordy Rose       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
30454569448SJordy Rose         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
30554569448SJordy Rose     }
30654569448SJordy Rose   } else
30754569448SJordy Rose     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
30854569448SJordy Rose 
30954569448SJordy Rose   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
310fa0734ecSArgyrios Kyrtzidis }
311fa0734ecSArgyrios Kyrtzidis 
312*2bbccca9SAdam Balogh // See if Sym is known to be a relation Rel with Bound.
313*2bbccca9SAdam Balogh static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
314*2bbccca9SAdam Balogh                          llvm::APSInt Bound, ProgramStateRef State) {
315*2bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
316*2bbccca9SAdam Balogh   SVal Result =
317*2bbccca9SAdam Balogh       SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
318*2bbccca9SAdam Balogh                       nonloc::ConcreteInt(Bound), SVB.getConditionType());
319*2bbccca9SAdam Balogh   if (auto DV = Result.getAs<DefinedSVal>()) {
320*2bbccca9SAdam Balogh     return !State->assume(*DV, false);
321*2bbccca9SAdam Balogh   }
322*2bbccca9SAdam Balogh   return false;
323*2bbccca9SAdam Balogh }
324*2bbccca9SAdam Balogh 
325*2bbccca9SAdam Balogh // See if Sym is known to be within [min/4, max/4], where min and max
326*2bbccca9SAdam Balogh // are the bounds of the symbol's integral type. With such symbols,
327*2bbccca9SAdam Balogh // some manipulations can be performed without the risk of overflow.
328*2bbccca9SAdam Balogh // assume() doesn't cause infinite recursion because we should be dealing
329*2bbccca9SAdam Balogh // with simpler symbols on every recursive call.
330*2bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(SymbolRef Sym,
331*2bbccca9SAdam Balogh                                            ProgramStateRef State) {
332*2bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
333*2bbccca9SAdam Balogh   BasicValueFactory &BV = SVB.getBasicValueFactory();
334*2bbccca9SAdam Balogh 
335*2bbccca9SAdam Balogh   QualType T = Sym->getType();
336*2bbccca9SAdam Balogh   assert(T->isSignedIntegerOrEnumerationType() &&
337*2bbccca9SAdam Balogh          "This only works with signed integers!");
338*2bbccca9SAdam Balogh   APSIntType AT = BV.getAPSIntType(T);
339*2bbccca9SAdam Balogh 
340*2bbccca9SAdam Balogh   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
341*2bbccca9SAdam Balogh   return isInRelation(BO_LE, Sym, Max, State) &&
342*2bbccca9SAdam Balogh          isInRelation(BO_GE, Sym, Min, State);
343*2bbccca9SAdam Balogh }
344*2bbccca9SAdam Balogh 
345*2bbccca9SAdam Balogh // Same for the concrete integers: see if I is within [min/4, max/4].
346*2bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
347*2bbccca9SAdam Balogh   APSIntType AT(I);
348*2bbccca9SAdam Balogh   assert(!AT.isUnsigned() &&
349*2bbccca9SAdam Balogh          "This only works with signed integers!");
350*2bbccca9SAdam Balogh 
351*2bbccca9SAdam Balogh   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
352*2bbccca9SAdam Balogh   return (I <= Max) && (I >= -Max);
353*2bbccca9SAdam Balogh }
354*2bbccca9SAdam Balogh 
355*2bbccca9SAdam Balogh static std::pair<SymbolRef, llvm::APSInt>
356*2bbccca9SAdam Balogh decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
357*2bbccca9SAdam Balogh   if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
358*2bbccca9SAdam Balogh     if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
359*2bbccca9SAdam Balogh       return std::make_pair(SymInt->getLHS(),
360*2bbccca9SAdam Balogh                             (SymInt->getOpcode() == BO_Add) ?
361*2bbccca9SAdam Balogh                             (SymInt->getRHS()) :
362*2bbccca9SAdam Balogh                             (-SymInt->getRHS()));
363*2bbccca9SAdam Balogh 
364*2bbccca9SAdam Balogh   // Fail to decompose: "reduce" the problem to the "$x + 0" case.
365*2bbccca9SAdam Balogh   return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
366*2bbccca9SAdam Balogh }
367*2bbccca9SAdam Balogh 
368*2bbccca9SAdam Balogh // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
369*2bbccca9SAdam Balogh // same signed integral type and no overflows occur (which should be checked
370*2bbccca9SAdam Balogh // by the caller).
371*2bbccca9SAdam Balogh static NonLoc doRearrangeUnchecked(ProgramStateRef State,
372*2bbccca9SAdam Balogh                                    BinaryOperator::Opcode Op,
373*2bbccca9SAdam Balogh                                    SymbolRef LSym, llvm::APSInt LInt,
374*2bbccca9SAdam Balogh                                    SymbolRef RSym, llvm::APSInt RInt) {
375*2bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
376*2bbccca9SAdam Balogh   BasicValueFactory &BV = SVB.getBasicValueFactory();
377*2bbccca9SAdam Balogh   SymbolManager &SymMgr = SVB.getSymbolManager();
378*2bbccca9SAdam Balogh 
379*2bbccca9SAdam Balogh   QualType SymTy = LSym->getType();
380*2bbccca9SAdam Balogh   assert(SymTy == RSym->getType() &&
381*2bbccca9SAdam Balogh          "Symbols are not of the same type!");
382*2bbccca9SAdam Balogh   assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
383*2bbccca9SAdam Balogh          "Integers are not of the same type as symbols!");
384*2bbccca9SAdam Balogh   assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
385*2bbccca9SAdam Balogh          "Integers are not of the same type as symbols!");
386*2bbccca9SAdam Balogh 
387*2bbccca9SAdam Balogh   QualType ResultTy;
388*2bbccca9SAdam Balogh   if (BinaryOperator::isComparisonOp(Op))
389*2bbccca9SAdam Balogh     ResultTy = SVB.getConditionType();
390*2bbccca9SAdam Balogh   else if (BinaryOperator::isAdditiveOp(Op))
391*2bbccca9SAdam Balogh     ResultTy = SymTy;
392*2bbccca9SAdam Balogh   else
393*2bbccca9SAdam Balogh     llvm_unreachable("Operation not suitable for unchecked rearrangement!");
394*2bbccca9SAdam Balogh 
395*2bbccca9SAdam Balogh   // FIXME: Can we use assume() without getting into an infinite recursion?
396*2bbccca9SAdam Balogh   if (LSym == RSym)
397*2bbccca9SAdam Balogh     return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
398*2bbccca9SAdam Balogh                            nonloc::ConcreteInt(RInt), ResultTy)
399*2bbccca9SAdam Balogh         .castAs<NonLoc>();
400*2bbccca9SAdam Balogh 
401*2bbccca9SAdam Balogh   SymbolRef ResultSym = nullptr;
402*2bbccca9SAdam Balogh   BinaryOperator::Opcode ResultOp;
403*2bbccca9SAdam Balogh   llvm::APSInt ResultInt;
404*2bbccca9SAdam Balogh   if (BinaryOperator::isComparisonOp(Op)) {
405*2bbccca9SAdam Balogh     // Prefer comparing to a non-negative number.
406*2bbccca9SAdam Balogh     // FIXME: Maybe it'd be better to have consistency in
407*2bbccca9SAdam Balogh     // "$x - $y" vs. "$y - $x" because those are solver's keys.
408*2bbccca9SAdam Balogh     if (LInt > RInt) {
409*2bbccca9SAdam Balogh       ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
410*2bbccca9SAdam Balogh       ResultOp = BinaryOperator::reverseComparisonOp(Op);
411*2bbccca9SAdam Balogh       ResultInt = LInt - RInt; // Opposite order!
412*2bbccca9SAdam Balogh     } else {
413*2bbccca9SAdam Balogh       ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
414*2bbccca9SAdam Balogh       ResultOp = Op;
415*2bbccca9SAdam Balogh       ResultInt = RInt - LInt; // Opposite order!
416*2bbccca9SAdam Balogh     }
417*2bbccca9SAdam Balogh   } else {
418*2bbccca9SAdam Balogh     ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
419*2bbccca9SAdam Balogh     ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
420*2bbccca9SAdam Balogh     ResultOp = BO_Add;
421*2bbccca9SAdam Balogh     // Bring back the cosmetic difference.
422*2bbccca9SAdam Balogh     if (ResultInt < 0) {
423*2bbccca9SAdam Balogh       ResultInt = -ResultInt;
424*2bbccca9SAdam Balogh       ResultOp = BO_Sub;
425*2bbccca9SAdam Balogh     } else if (ResultInt == 0) {
426*2bbccca9SAdam Balogh       // Shortcut: Simplify "$x + 0" to "$x".
427*2bbccca9SAdam Balogh       return nonloc::SymbolVal(ResultSym);
428*2bbccca9SAdam Balogh     }
429*2bbccca9SAdam Balogh   }
430*2bbccca9SAdam Balogh   const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
431*2bbccca9SAdam Balogh   return nonloc::SymbolVal(
432*2bbccca9SAdam Balogh       SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
433*2bbccca9SAdam Balogh }
434*2bbccca9SAdam Balogh 
435*2bbccca9SAdam Balogh // Rearrange if symbol type matches the result type and if the operator is a
436*2bbccca9SAdam Balogh // comparison operator, both symbol and constant must be within constant
437*2bbccca9SAdam Balogh // overflow bounds.
438*2bbccca9SAdam Balogh static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
439*2bbccca9SAdam Balogh                             SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
440*2bbccca9SAdam Balogh   return Sym->getType() == Ty &&
441*2bbccca9SAdam Balogh     (!BinaryOperator::isComparisonOp(Op) ||
442*2bbccca9SAdam Balogh      (isWithinConstantOverflowBounds(Sym, State) &&
443*2bbccca9SAdam Balogh       isWithinConstantOverflowBounds(Int)));
444*2bbccca9SAdam Balogh }
445*2bbccca9SAdam Balogh 
446*2bbccca9SAdam Balogh static Optional<NonLoc> tryRearrange(ProgramStateRef State,
447*2bbccca9SAdam Balogh                                      BinaryOperator::Opcode Op, NonLoc Lhs,
448*2bbccca9SAdam Balogh                                      NonLoc Rhs, QualType ResultTy) {
449*2bbccca9SAdam Balogh   ProgramStateManager &StateMgr = State->getStateManager();
450*2bbccca9SAdam Balogh   SValBuilder &SVB = StateMgr.getSValBuilder();
451*2bbccca9SAdam Balogh 
452*2bbccca9SAdam Balogh   // We expect everything to be of the same type - this type.
453*2bbccca9SAdam Balogh   QualType SingleTy;
454*2bbccca9SAdam Balogh 
455*2bbccca9SAdam Balogh   auto &Opts =
456*2bbccca9SAdam Balogh     StateMgr.getOwningEngine()->getAnalysisManager().getAnalyzerOptions();
457*2bbccca9SAdam Balogh 
458*2bbccca9SAdam Balogh   SymbolRef LSym = Lhs.getAsSymbol();
459*2bbccca9SAdam Balogh   if (!LSym)
460*2bbccca9SAdam Balogh     return None;
461*2bbccca9SAdam Balogh 
462*2bbccca9SAdam Balogh   // Always rearrange additive operations but rearrange comparisons only if
463*2bbccca9SAdam Balogh   // option is set.
464*2bbccca9SAdam Balogh   if (BinaryOperator::isComparisonOp(Op) &&
465*2bbccca9SAdam Balogh       Opts.shouldAggressivelySimplifyRelationalComparison()) {
466*2bbccca9SAdam Balogh     SingleTy = LSym->getType();
467*2bbccca9SAdam Balogh     if (ResultTy != SVB.getConditionType())
468*2bbccca9SAdam Balogh       return None;
469*2bbccca9SAdam Balogh     // Initialize SingleTy later with a symbol's type.
470*2bbccca9SAdam Balogh   } else if (BinaryOperator::isAdditiveOp(Op)) {
471*2bbccca9SAdam Balogh     SingleTy = ResultTy;
472*2bbccca9SAdam Balogh     // Substracting unsigned integers is a nightmare.
473*2bbccca9SAdam Balogh     if (!SingleTy->isSignedIntegerOrEnumerationType())
474*2bbccca9SAdam Balogh       return None;
475*2bbccca9SAdam Balogh   } else {
476*2bbccca9SAdam Balogh     // Don't rearrange other operations.
477*2bbccca9SAdam Balogh     return None;
478*2bbccca9SAdam Balogh   }
479*2bbccca9SAdam Balogh 
480*2bbccca9SAdam Balogh   assert(!SingleTy.isNull() && "We should have figured out the type by now!");
481*2bbccca9SAdam Balogh 
482*2bbccca9SAdam Balogh   SymbolRef RSym = Rhs.getAsSymbol();
483*2bbccca9SAdam Balogh   if (!RSym || RSym->getType() != SingleTy)
484*2bbccca9SAdam Balogh     return None;
485*2bbccca9SAdam Balogh 
486*2bbccca9SAdam Balogh   BasicValueFactory &BV = State->getBasicVals();
487*2bbccca9SAdam Balogh   llvm::APSInt LInt, RInt;
488*2bbccca9SAdam Balogh   std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
489*2bbccca9SAdam Balogh   std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
490*2bbccca9SAdam Balogh   if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
491*2bbccca9SAdam Balogh       !shouldRearrange(State, Op, RSym, RInt, SingleTy))
492*2bbccca9SAdam Balogh     return None;
493*2bbccca9SAdam Balogh 
494*2bbccca9SAdam Balogh   // We know that no overflows can occur anymore.
495*2bbccca9SAdam Balogh   return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
496*2bbccca9SAdam Balogh }
497*2bbccca9SAdam Balogh 
49849b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
499fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
500fa0734ecSArgyrios Kyrtzidis                                   NonLoc lhs, NonLoc rhs,
501fa0734ecSArgyrios Kyrtzidis                                   QualType resultTy)  {
502f0e9ca86SAnna Zaks   NonLoc InputLHS = lhs;
503f0e9ca86SAnna Zaks   NonLoc InputRHS = rhs;
504f0e9ca86SAnna Zaks 
505fa0734ecSArgyrios Kyrtzidis   // Handle trivial case where left-side and right-side are the same.
506fa0734ecSArgyrios Kyrtzidis   if (lhs == rhs)
507fa0734ecSArgyrios Kyrtzidis     switch (op) {
508fa0734ecSArgyrios Kyrtzidis       default:
509fa0734ecSArgyrios Kyrtzidis         break;
510fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
511fa0734ecSArgyrios Kyrtzidis       case BO_LE:
512fa0734ecSArgyrios Kyrtzidis       case BO_GE:
513fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
514fa0734ecSArgyrios Kyrtzidis       case BO_LT:
515fa0734ecSArgyrios Kyrtzidis       case BO_GT:
516fa0734ecSArgyrios Kyrtzidis       case BO_NE:
517fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
518fa0734ecSArgyrios Kyrtzidis       case BO_Xor:
519fa0734ecSArgyrios Kyrtzidis       case BO_Sub:
5207523d1a8SJordan Rose         if (resultTy->isIntegralOrEnumerationType())
521fa0734ecSArgyrios Kyrtzidis           return makeIntVal(0, resultTy);
5227523d1a8SJordan Rose         return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
523fa0734ecSArgyrios Kyrtzidis       case BO_Or:
524fa0734ecSArgyrios Kyrtzidis       case BO_And:
5255ad574c0SZhanyong Wan         return evalCastFromNonLoc(lhs, resultTy);
526fa0734ecSArgyrios Kyrtzidis     }
527fa0734ecSArgyrios Kyrtzidis 
528fa0734ecSArgyrios Kyrtzidis   while (1) {
529fa0734ecSArgyrios Kyrtzidis     switch (lhs.getSubKind()) {
530fa0734ecSArgyrios Kyrtzidis     default:
531b35437a8SAnna Zaks       return makeSymExprValNN(state, op, lhs, rhs, resultTy);
53264c01f7bSDevin Coughlin     case nonloc::PointerToMemberKind: {
53364c01f7bSDevin Coughlin       assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
53464c01f7bSDevin Coughlin              "Both SVals should have pointer-to-member-type");
53564c01f7bSDevin Coughlin       auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
53664c01f7bSDevin Coughlin            RPTM = rhs.castAs<nonloc::PointerToMember>();
53764c01f7bSDevin Coughlin       auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
53864c01f7bSDevin Coughlin       switch (op) {
53964c01f7bSDevin Coughlin         case BO_EQ:
54064c01f7bSDevin Coughlin           return makeTruthVal(LPTMD == RPTMD, resultTy);
54164c01f7bSDevin Coughlin         case BO_NE:
54264c01f7bSDevin Coughlin           return makeTruthVal(LPTMD != RPTMD, resultTy);
54364c01f7bSDevin Coughlin         default:
54464c01f7bSDevin Coughlin           return UnknownVal();
54564c01f7bSDevin Coughlin       }
54664c01f7bSDevin Coughlin     }
547fa0734ecSArgyrios Kyrtzidis     case nonloc::LocAsIntegerKind: {
5482fdacbc5SDavid Blaikie       Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
549fa0734ecSArgyrios Kyrtzidis       switch (rhs.getSubKind()) {
550fa0734ecSArgyrios Kyrtzidis         case nonloc::LocAsIntegerKind:
55118d77984SAlexander Shaposhnikov           // FIXME: at the moment the implementation
55218d77984SAlexander Shaposhnikov           // of modeling "pointers as integers" is not complete.
55318d77984SAlexander Shaposhnikov           if (!BinaryOperator::isComparisonOp(op))
55418d77984SAlexander Shaposhnikov             return UnknownVal();
555fa0734ecSArgyrios Kyrtzidis           return evalBinOpLL(state, op, lhsL,
5562fdacbc5SDavid Blaikie                              rhs.castAs<nonloc::LocAsInteger>().getLoc(),
557fa0734ecSArgyrios Kyrtzidis                              resultTy);
558fa0734ecSArgyrios Kyrtzidis         case nonloc::ConcreteIntKind: {
55918d77984SAlexander Shaposhnikov           // FIXME: at the moment the implementation
56018d77984SAlexander Shaposhnikov           // of modeling "pointers as integers" is not complete.
56118d77984SAlexander Shaposhnikov           if (!BinaryOperator::isComparisonOp(op))
56218d77984SAlexander Shaposhnikov             return UnknownVal();
563fa0734ecSArgyrios Kyrtzidis           // Transform the integer into a location and compare.
5647333a9eaSArtem Dergachev           // FIXME: This only makes sense for comparisons. If we want to, say,
5657333a9eaSArtem Dergachev           // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
5667333a9eaSArtem Dergachev           // then pack it back into a LocAsInteger.
5672fdacbc5SDavid Blaikie           llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
5687e3c3ea3SJordy Rose           BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
569fa0734ecSArgyrios Kyrtzidis           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
570fa0734ecSArgyrios Kyrtzidis         }
571fa0734ecSArgyrios Kyrtzidis         default:
572fa0734ecSArgyrios Kyrtzidis           switch (op) {
573fa0734ecSArgyrios Kyrtzidis             case BO_EQ:
574fa0734ecSArgyrios Kyrtzidis               return makeTruthVal(false, resultTy);
575fa0734ecSArgyrios Kyrtzidis             case BO_NE:
576fa0734ecSArgyrios Kyrtzidis               return makeTruthVal(true, resultTy);
577fa0734ecSArgyrios Kyrtzidis             default:
578fa0734ecSArgyrios Kyrtzidis               // This case also handles pointer arithmetic.
579f0e9ca86SAnna Zaks               return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
580fa0734ecSArgyrios Kyrtzidis           }
581fa0734ecSArgyrios Kyrtzidis       }
582fa0734ecSArgyrios Kyrtzidis     }
583d066f79cSAnna Zaks     case nonloc::ConcreteIntKind: {
5842fdacbc5SDavid Blaikie       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
585d066f79cSAnna Zaks 
58654569448SJordy Rose       // If we're dealing with two known constants, just perform the operation.
58754569448SJordy Rose       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
58854569448SJordy Rose         llvm::APSInt RHSValue = *KnownRHSValue;
58954569448SJordy Rose         if (BinaryOperator::isComparisonOp(op)) {
59054569448SJordy Rose           // We're looking for a type big enough to compare the two values.
5917e3c3ea3SJordy Rose           // FIXME: This is not correct. char + short will result in a promotion
5927e3c3ea3SJordy Rose           // to int. Unfortunately we have lost types by this point.
5937e3c3ea3SJordy Rose           APSIntType CompareType = std::max(APSIntType(LHSValue),
5947e3c3ea3SJordy Rose                                             APSIntType(RHSValue));
5957e3c3ea3SJordy Rose           CompareType.apply(LHSValue);
5967e3c3ea3SJordy Rose           CompareType.apply(RHSValue);
59754569448SJordy Rose         } else if (!BinaryOperator::isShiftOp(op)) {
5987e3c3ea3SJordy Rose           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
5997e3c3ea3SJordy Rose           IntType.apply(LHSValue);
6007e3c3ea3SJordy Rose           IntType.apply(RHSValue);
601d066f79cSAnna Zaks         }
602d066f79cSAnna Zaks 
60354569448SJordy Rose         const llvm::APSInt *Result =
60454569448SJordy Rose           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
60554569448SJordy Rose         if (!Result)
60654569448SJordy Rose           return UndefinedVal();
60754569448SJordy Rose 
60854569448SJordy Rose         return nonloc::ConcreteInt(*Result);
60954569448SJordy Rose       }
610d066f79cSAnna Zaks 
611d066f79cSAnna Zaks       // Swap the left and right sides and flip the operator if doing so
612d066f79cSAnna Zaks       // allows us to better reason about the expression (this is a form
613d066f79cSAnna Zaks       // of expression canonicalization).
614d066f79cSAnna Zaks       // While we're at it, catch some special cases for non-commutative ops.
615d066f79cSAnna Zaks       switch (op) {
616d066f79cSAnna Zaks       case BO_LT:
617d066f79cSAnna Zaks       case BO_GT:
618d066f79cSAnna Zaks       case BO_LE:
619d066f79cSAnna Zaks       case BO_GE:
620604d0bbbSJordan Rose         op = BinaryOperator::reverseComparisonOp(op);
62154569448SJordy Rose         // FALL-THROUGH
622d066f79cSAnna Zaks       case BO_EQ:
623d066f79cSAnna Zaks       case BO_NE:
624d066f79cSAnna Zaks       case BO_Add:
625d066f79cSAnna Zaks       case BO_Mul:
626d066f79cSAnna Zaks       case BO_And:
627d066f79cSAnna Zaks       case BO_Xor:
628d066f79cSAnna Zaks       case BO_Or:
62954569448SJordy Rose         std::swap(lhs, rhs);
630d066f79cSAnna Zaks         continue;
631d066f79cSAnna Zaks       case BO_Shr:
63254569448SJordy Rose         // (~0)>>a
63354569448SJordy Rose         if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
63454569448SJordy Rose           return evalCastFromNonLoc(lhs, resultTy);
635d066f79cSAnna Zaks         // FALL-THROUGH
636d066f79cSAnna Zaks       case BO_Shl:
63754569448SJordy Rose         // 0<<a and 0>>a
63854569448SJordy Rose         if (LHSValue == 0)
63954569448SJordy Rose           return evalCastFromNonLoc(lhs, resultTy);
640f0e9ca86SAnna Zaks         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
641d066f79cSAnna Zaks       default:
642f0e9ca86SAnna Zaks         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
643d066f79cSAnna Zaks       }
644d066f79cSAnna Zaks     }
645d066f79cSAnna Zaks     case nonloc::SymbolValKind: {
64654569448SJordy Rose       // We only handle LHS as simple symbols or SymIntExprs.
6472fdacbc5SDavid Blaikie       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
648d066f79cSAnna Zaks 
649d066f79cSAnna Zaks       // LHS is a symbolic expression.
65054569448SJordy Rose       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
651fa0734ecSArgyrios Kyrtzidis 
652fa0734ecSArgyrios Kyrtzidis         // Is this a logical not? (!x is represented as x == 0.)
653fa0734ecSArgyrios Kyrtzidis         if (op == BO_EQ && rhs.isZeroConstant()) {
654fa0734ecSArgyrios Kyrtzidis           // We know how to negate certain expressions. Simplify them here.
655fa0734ecSArgyrios Kyrtzidis 
656fa0734ecSArgyrios Kyrtzidis           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
657fa0734ecSArgyrios Kyrtzidis           switch (opc) {
658fa0734ecSArgyrios Kyrtzidis           default:
659fa0734ecSArgyrios Kyrtzidis             // We don't know how to negate this operation.
660fa0734ecSArgyrios Kyrtzidis             // Just handle it as if it were a normal comparison to 0.
661fa0734ecSArgyrios Kyrtzidis             break;
662fa0734ecSArgyrios Kyrtzidis           case BO_LAnd:
663fa0734ecSArgyrios Kyrtzidis           case BO_LOr:
66483d382b1SDavid Blaikie             llvm_unreachable("Logical operators handled by branching logic.");
665fa0734ecSArgyrios Kyrtzidis           case BO_Assign:
666fa0734ecSArgyrios Kyrtzidis           case BO_MulAssign:
667fa0734ecSArgyrios Kyrtzidis           case BO_DivAssign:
668fa0734ecSArgyrios Kyrtzidis           case BO_RemAssign:
669fa0734ecSArgyrios Kyrtzidis           case BO_AddAssign:
670fa0734ecSArgyrios Kyrtzidis           case BO_SubAssign:
671fa0734ecSArgyrios Kyrtzidis           case BO_ShlAssign:
672fa0734ecSArgyrios Kyrtzidis           case BO_ShrAssign:
673fa0734ecSArgyrios Kyrtzidis           case BO_AndAssign:
674fa0734ecSArgyrios Kyrtzidis           case BO_XorAssign:
675fa0734ecSArgyrios Kyrtzidis           case BO_OrAssign:
676fa0734ecSArgyrios Kyrtzidis           case BO_Comma:
67783d382b1SDavid Blaikie             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
678fa0734ecSArgyrios Kyrtzidis           case BO_PtrMemD:
679fa0734ecSArgyrios Kyrtzidis           case BO_PtrMemI:
68083d382b1SDavid Blaikie             llvm_unreachable("Pointer arithmetic not handled here.");
681fa0734ecSArgyrios Kyrtzidis           case BO_LT:
682fa0734ecSArgyrios Kyrtzidis           case BO_GT:
683fa0734ecSArgyrios Kyrtzidis           case BO_LE:
684fa0734ecSArgyrios Kyrtzidis           case BO_GE:
685fa0734ecSArgyrios Kyrtzidis           case BO_EQ:
686fa0734ecSArgyrios Kyrtzidis           case BO_NE:
687dc16628cSJordan Rose             assert(resultTy->isBooleanType() ||
688dc16628cSJordan Rose                    resultTy == getConditionType());
689dc16628cSJordan Rose             assert(symIntExpr->getType()->isBooleanType() ||
690dc16628cSJordan Rose                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
691dc16628cSJordan Rose                                                        getConditionType()));
692fa0734ecSArgyrios Kyrtzidis             // Negate the comparison and make a value.
693604d0bbbSJordan Rose             opc = BinaryOperator::negateComparisonOp(opc);
694fa0734ecSArgyrios Kyrtzidis             return makeNonLoc(symIntExpr->getLHS(), opc,
695fa0734ecSArgyrios Kyrtzidis                 symIntExpr->getRHS(), resultTy);
696fa0734ecSArgyrios Kyrtzidis           }
697fa0734ecSArgyrios Kyrtzidis         }
698fa0734ecSArgyrios Kyrtzidis 
699fa0734ecSArgyrios Kyrtzidis         // For now, only handle expressions whose RHS is a constant.
70054569448SJordy Rose         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
701fa0734ecSArgyrios Kyrtzidis           // If both the LHS and the current expression are additive,
70254569448SJordy Rose           // fold their constants and try again.
703fa0734ecSArgyrios Kyrtzidis           if (BinaryOperator::isAdditiveOp(op)) {
704fa0734ecSArgyrios Kyrtzidis             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
705fa0734ecSArgyrios Kyrtzidis             if (BinaryOperator::isAdditiveOp(lop)) {
70654569448SJordy Rose               // Convert the two constants to a common type, then combine them.
70754569448SJordy Rose 
708fa0734ecSArgyrios Kyrtzidis               // resultTy may not be the best type to convert to, but it's
709fa0734ecSArgyrios Kyrtzidis               // probably the best choice in expressions with mixed type
710fa0734ecSArgyrios Kyrtzidis               // (such as x+1U+2LL). The rules for implicit conversions should
711fa0734ecSArgyrios Kyrtzidis               // choose a reasonable type to preserve the expression, and will
712fa0734ecSArgyrios Kyrtzidis               // at least match how the value is going to be used.
7137e3c3ea3SJordy Rose               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
7147e3c3ea3SJordy Rose               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
7157e3c3ea3SJordy Rose               const llvm::APSInt &second = IntType.convert(*RHSValue);
71654569448SJordy Rose 
717fa0734ecSArgyrios Kyrtzidis               const llvm::APSInt *newRHS;
718fa0734ecSArgyrios Kyrtzidis               if (lop == op)
719fa0734ecSArgyrios Kyrtzidis                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
720fa0734ecSArgyrios Kyrtzidis               else
721fa0734ecSArgyrios Kyrtzidis                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
72254569448SJordy Rose 
72354569448SJordy Rose               assert(newRHS && "Invalid operation despite common type!");
72454569448SJordy Rose               rhs = nonloc::ConcreteInt(*newRHS);
72554569448SJordy Rose               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
72654569448SJordy Rose               op = lop;
72754569448SJordy Rose               continue;
728fa0734ecSArgyrios Kyrtzidis             }
729fa0734ecSArgyrios Kyrtzidis           }
730fa0734ecSArgyrios Kyrtzidis 
73154569448SJordy Rose           // Otherwise, make a SymIntExpr out of the expression.
73254569448SJordy Rose           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
73354569448SJordy Rose         }
7343b4c3ea2SJordan Rose       }
735fa0734ecSArgyrios Kyrtzidis 
7363b4c3ea2SJordan Rose       // Does the symbolic expression simplify to a constant?
7373b4c3ea2SJordan Rose       // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
7383b4c3ea2SJordan Rose       // and try again.
73912294f8dSArtem Dergachev       SVal simplifiedLhs = simplifySVal(state, lhs);
74012294f8dSArtem Dergachev       if (simplifiedLhs != lhs)
74112294f8dSArtem Dergachev         if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
74212294f8dSArtem Dergachev           lhs = *simplifiedLhsAsNonLoc;
743fa0734ecSArgyrios Kyrtzidis           continue;
744fa0734ecSArgyrios Kyrtzidis         }
745fa0734ecSArgyrios Kyrtzidis 
74654569448SJordy Rose       // Is the RHS a constant?
74754569448SJordy Rose       if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
74854569448SJordy Rose         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
749fa0734ecSArgyrios Kyrtzidis 
750*2bbccca9SAdam Balogh       if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
751*2bbccca9SAdam Balogh         return *V;
752*2bbccca9SAdam Balogh 
75354569448SJordy Rose       // Give up -- this is not a symbolic expression we can handle.
754f0e9ca86SAnna Zaks       return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
755fa0734ecSArgyrios Kyrtzidis     }
756fa0734ecSArgyrios Kyrtzidis     }
757fa0734ecSArgyrios Kyrtzidis   }
758fa0734ecSArgyrios Kyrtzidis }
759fa0734ecSArgyrios Kyrtzidis 
760bac964e1SAnna Zaks static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
761bac964e1SAnna Zaks                                             const FieldRegion *RightFR,
762bac964e1SAnna Zaks                                             BinaryOperator::Opcode op,
763bac964e1SAnna Zaks                                             QualType resultTy,
764bac964e1SAnna Zaks                                             SimpleSValBuilder &SVB) {
765bac964e1SAnna Zaks   // Only comparisons are meaningful here!
766bac964e1SAnna Zaks   if (!BinaryOperator::isComparisonOp(op))
767bac964e1SAnna Zaks     return UnknownVal();
768bac964e1SAnna Zaks 
769bac964e1SAnna Zaks   // Next, see if the two FRs have the same super-region.
770bac964e1SAnna Zaks   // FIXME: This doesn't handle casts yet, and simply stripping the casts
771bac964e1SAnna Zaks   // doesn't help.
772bac964e1SAnna Zaks   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
773bac964e1SAnna Zaks     return UnknownVal();
774bac964e1SAnna Zaks 
775bac964e1SAnna Zaks   const FieldDecl *LeftFD = LeftFR->getDecl();
776bac964e1SAnna Zaks   const FieldDecl *RightFD = RightFR->getDecl();
777bac964e1SAnna Zaks   const RecordDecl *RD = LeftFD->getParent();
778bac964e1SAnna Zaks 
779bac964e1SAnna Zaks   // Make sure the two FRs are from the same kind of record. Just in case!
780bac964e1SAnna Zaks   // FIXME: This is probably where inheritance would be a problem.
781bac964e1SAnna Zaks   if (RD != RightFD->getParent())
782bac964e1SAnna Zaks     return UnknownVal();
783bac964e1SAnna Zaks 
784bac964e1SAnna Zaks   // We know for sure that the two fields are not the same, since that
785bac964e1SAnna Zaks   // would have given us the same SVal.
786bac964e1SAnna Zaks   if (op == BO_EQ)
787bac964e1SAnna Zaks     return SVB.makeTruthVal(false, resultTy);
788bac964e1SAnna Zaks   if (op == BO_NE)
789bac964e1SAnna Zaks     return SVB.makeTruthVal(true, resultTy);
790bac964e1SAnna Zaks 
791bac964e1SAnna Zaks   // Iterate through the fields and see which one comes first.
792bac964e1SAnna Zaks   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
793bac964e1SAnna Zaks   // members and the units in which bit-fields reside have addresses that
794bac964e1SAnna Zaks   // increase in the order in which they are declared."
795bac964e1SAnna Zaks   bool leftFirst = (op == BO_LT || op == BO_LE);
796e8a8baefSAaron Ballman   for (const auto *I : RD->fields()) {
797e8a8baefSAaron Ballman     if (I == LeftFD)
798bac964e1SAnna Zaks       return SVB.makeTruthVal(leftFirst, resultTy);
799e8a8baefSAaron Ballman     if (I == RightFD)
800bac964e1SAnna Zaks       return SVB.makeTruthVal(!leftFirst, resultTy);
801bac964e1SAnna Zaks   }
802bac964e1SAnna Zaks 
803bac964e1SAnna Zaks   llvm_unreachable("Fields not found in parent record's definition");
804bac964e1SAnna Zaks }
805bac964e1SAnna Zaks 
806fa0734ecSArgyrios Kyrtzidis // FIXME: all this logic will change if/when we have MemRegion::getLocation().
80749b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
808fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
809fa0734ecSArgyrios Kyrtzidis                                   Loc lhs, Loc rhs,
810fa0734ecSArgyrios Kyrtzidis                                   QualType resultTy) {
811fa0734ecSArgyrios Kyrtzidis   // Only comparisons and subtractions are valid operations on two pointers.
812fa0734ecSArgyrios Kyrtzidis   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
813fa0734ecSArgyrios Kyrtzidis   // However, if a pointer is casted to an integer, evalBinOpNN may end up
814fa0734ecSArgyrios Kyrtzidis   // calling this function with another operation (PR7527). We don't attempt to
815fa0734ecSArgyrios Kyrtzidis   // model this for now, but it could be useful, particularly when the
816fa0734ecSArgyrios Kyrtzidis   // "location" is actually an integer value that's been passed through a void*.
817fa0734ecSArgyrios Kyrtzidis   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
818fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
819fa0734ecSArgyrios Kyrtzidis 
820fa0734ecSArgyrios Kyrtzidis   // Special cases for when both sides are identical.
821fa0734ecSArgyrios Kyrtzidis   if (lhs == rhs) {
822fa0734ecSArgyrios Kyrtzidis     switch (op) {
823fa0734ecSArgyrios Kyrtzidis     default:
82483d382b1SDavid Blaikie       llvm_unreachable("Unimplemented operation for two identical values");
825fa0734ecSArgyrios Kyrtzidis     case BO_Sub:
826fa0734ecSArgyrios Kyrtzidis       return makeZeroVal(resultTy);
827fa0734ecSArgyrios Kyrtzidis     case BO_EQ:
828fa0734ecSArgyrios Kyrtzidis     case BO_LE:
829fa0734ecSArgyrios Kyrtzidis     case BO_GE:
830fa0734ecSArgyrios Kyrtzidis       return makeTruthVal(true, resultTy);
831fa0734ecSArgyrios Kyrtzidis     case BO_NE:
832fa0734ecSArgyrios Kyrtzidis     case BO_LT:
833fa0734ecSArgyrios Kyrtzidis     case BO_GT:
834fa0734ecSArgyrios Kyrtzidis       return makeTruthVal(false, resultTy);
835fa0734ecSArgyrios Kyrtzidis     }
836fa0734ecSArgyrios Kyrtzidis   }
837fa0734ecSArgyrios Kyrtzidis 
838fa0734ecSArgyrios Kyrtzidis   switch (lhs.getSubKind()) {
839fa0734ecSArgyrios Kyrtzidis   default:
84083d382b1SDavid Blaikie     llvm_unreachable("Ordering not implemented for this Loc.");
841fa0734ecSArgyrios Kyrtzidis 
842fa0734ecSArgyrios Kyrtzidis   case loc::GotoLabelKind:
843fa0734ecSArgyrios Kyrtzidis     // The only thing we know about labels is that they're non-null.
844fa0734ecSArgyrios Kyrtzidis     if (rhs.isZeroConstant()) {
845fa0734ecSArgyrios Kyrtzidis       switch (op) {
846fa0734ecSArgyrios Kyrtzidis       default:
847fa0734ecSArgyrios Kyrtzidis         break;
848fa0734ecSArgyrios Kyrtzidis       case BO_Sub:
8495ad574c0SZhanyong Wan         return evalCastFromLoc(lhs, resultTy);
850fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
851fa0734ecSArgyrios Kyrtzidis       case BO_LE:
852fa0734ecSArgyrios Kyrtzidis       case BO_LT:
853fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
854fa0734ecSArgyrios Kyrtzidis       case BO_NE:
855fa0734ecSArgyrios Kyrtzidis       case BO_GT:
856fa0734ecSArgyrios Kyrtzidis       case BO_GE:
857fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
858fa0734ecSArgyrios Kyrtzidis       }
859fa0734ecSArgyrios Kyrtzidis     }
860fa0734ecSArgyrios Kyrtzidis     // There may be two labels for the same location, and a function region may
861fa0734ecSArgyrios Kyrtzidis     // have the same address as a label at the start of the function (depending
862fa0734ecSArgyrios Kyrtzidis     // on the ABI).
863fa0734ecSArgyrios Kyrtzidis     // FIXME: we can probably do a comparison against other MemRegions, though.
864fa0734ecSArgyrios Kyrtzidis     // FIXME: is there a way to tell if two labels refer to the same location?
865fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
866fa0734ecSArgyrios Kyrtzidis 
867fa0734ecSArgyrios Kyrtzidis   case loc::ConcreteIntKind: {
868fa0734ecSArgyrios Kyrtzidis     // If one of the operands is a symbol and the other is a constant,
869fa0734ecSArgyrios Kyrtzidis     // build an expression for use by the constraint manager.
870fa0734ecSArgyrios Kyrtzidis     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
871c0402c69SDominic Chen       // We can only build expressions with symbols on the left,
872c0402c69SDominic Chen       // so we need a reversible operator.
873c70f1d63SRichard Smith       if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
874c0402c69SDominic Chen         return UnknownVal();
87535610d21SDominic Chen 
876c0402c69SDominic Chen       const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
877604d0bbbSJordan Rose       op = BinaryOperator::reverseComparisonOp(op);
878604d0bbbSJordan Rose       return makeNonLoc(rSym, op, lVal, resultTy);
879fa0734ecSArgyrios Kyrtzidis     }
880fa0734ecSArgyrios Kyrtzidis 
881fa0734ecSArgyrios Kyrtzidis     // If both operands are constants, just perform the operation.
88205785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
8832fdacbc5SDavid Blaikie       SVal ResultVal =
8842fdacbc5SDavid Blaikie           lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
8858eca04b2SJordan Rose       if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
8868eca04b2SJordan Rose         return evalCastFromNonLoc(*Result, resultTy);
8878eca04b2SJordan Rose 
8888eca04b2SJordan Rose       assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
889fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
890fa0734ecSArgyrios Kyrtzidis     }
891fa0734ecSArgyrios Kyrtzidis 
892fa0734ecSArgyrios Kyrtzidis     // Special case comparisons against NULL.
893fa0734ecSArgyrios Kyrtzidis     // This must come after the test if the RHS is a symbol, which is used to
894fa0734ecSArgyrios Kyrtzidis     // build constraints. The address of any non-symbolic region is guaranteed
895fa0734ecSArgyrios Kyrtzidis     // to be non-NULL, as is any label.
8962fdacbc5SDavid Blaikie     assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
897fa0734ecSArgyrios Kyrtzidis     if (lhs.isZeroConstant()) {
898fa0734ecSArgyrios Kyrtzidis       switch (op) {
899fa0734ecSArgyrios Kyrtzidis       default:
900fa0734ecSArgyrios Kyrtzidis         break;
901fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
902fa0734ecSArgyrios Kyrtzidis       case BO_GT:
903fa0734ecSArgyrios Kyrtzidis       case BO_GE:
904fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
905fa0734ecSArgyrios Kyrtzidis       case BO_NE:
906fa0734ecSArgyrios Kyrtzidis       case BO_LT:
907fa0734ecSArgyrios Kyrtzidis       case BO_LE:
908fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
909fa0734ecSArgyrios Kyrtzidis       }
910fa0734ecSArgyrios Kyrtzidis     }
911fa0734ecSArgyrios Kyrtzidis 
912fa0734ecSArgyrios Kyrtzidis     // Comparing an arbitrary integer to a region or label address is
913fa0734ecSArgyrios Kyrtzidis     // completely unknowable.
914fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
915fa0734ecSArgyrios Kyrtzidis   }
91673f018e3SArtem Dergachev   case loc::MemRegionValKind: {
91705785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
918fa0734ecSArgyrios Kyrtzidis       // If one of the operands is a symbol and the other is a constant,
919fa0734ecSArgyrios Kyrtzidis       // build an expression for use by the constraint manager.
920f4963ff1SAlexander Shaposhnikov       if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
921f4963ff1SAlexander Shaposhnikov         if (BinaryOperator::isComparisonOp(op))
922fa0734ecSArgyrios Kyrtzidis           return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
923f4963ff1SAlexander Shaposhnikov         return UnknownVal();
924f4963ff1SAlexander Shaposhnikov       }
925fa0734ecSArgyrios Kyrtzidis       // Special case comparisons to NULL.
926fa0734ecSArgyrios Kyrtzidis       // This must come after the test if the LHS is a symbol, which is used to
927fa0734ecSArgyrios Kyrtzidis       // build constraints. The address of any non-symbolic region is guaranteed
928fa0734ecSArgyrios Kyrtzidis       // to be non-NULL.
929fa0734ecSArgyrios Kyrtzidis       if (rInt->isZeroConstant()) {
930acd080b9SJordan Rose         if (op == BO_Sub)
9315ad574c0SZhanyong Wan           return evalCastFromLoc(lhs, resultTy);
932acd080b9SJordan Rose 
933acd080b9SJordan Rose         if (BinaryOperator::isComparisonOp(op)) {
934acd080b9SJordan Rose           QualType boolType = getContext().BoolTy;
935acd080b9SJordan Rose           NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
936acd080b9SJordan Rose           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
937acd080b9SJordan Rose           return evalBinOpNN(state, op, l, r, resultTy);
938fa0734ecSArgyrios Kyrtzidis         }
939fa0734ecSArgyrios Kyrtzidis       }
940fa0734ecSArgyrios Kyrtzidis 
941fa0734ecSArgyrios Kyrtzidis       // Comparing a region to an arbitrary integer is completely unknowable.
942fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
943fa0734ecSArgyrios Kyrtzidis     }
944fa0734ecSArgyrios Kyrtzidis 
945fa0734ecSArgyrios Kyrtzidis     // Get both values as regions, if possible.
946fa0734ecSArgyrios Kyrtzidis     const MemRegion *LeftMR = lhs.getAsRegion();
94773f018e3SArtem Dergachev     assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
948fa0734ecSArgyrios Kyrtzidis 
949fa0734ecSArgyrios Kyrtzidis     const MemRegion *RightMR = rhs.getAsRegion();
950fa0734ecSArgyrios Kyrtzidis     if (!RightMR)
951fa0734ecSArgyrios Kyrtzidis       // The RHS is probably a label, which in theory could address a region.
952fa0734ecSArgyrios Kyrtzidis       // FIXME: we can probably make a more useful statement about non-code
953fa0734ecSArgyrios Kyrtzidis       // regions, though.
954fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
955fa0734ecSArgyrios Kyrtzidis 
956fa0734ecSArgyrios Kyrtzidis     const MemRegion *LeftBase = LeftMR->getBaseRegion();
957fa0734ecSArgyrios Kyrtzidis     const MemRegion *RightBase = RightMR->getBaseRegion();
9583b4c3ea2SJordan Rose     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
9593b4c3ea2SJordan Rose     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
9603b4c3ea2SJordan Rose     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
9613563fde6SAnna Zaks 
9623563fde6SAnna Zaks     // If the two regions are from different known memory spaces they cannot be
9633563fde6SAnna Zaks     // equal. Also, assume that no symbolic region (whose memory space is
9643563fde6SAnna Zaks     // unknown) is on the stack.
9653563fde6SAnna Zaks     if (LeftMS != RightMS &&
9663563fde6SAnna Zaks         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
9673563fde6SAnna Zaks          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
968fa0734ecSArgyrios Kyrtzidis       switch (op) {
969fa0734ecSArgyrios Kyrtzidis       default:
970fa0734ecSArgyrios Kyrtzidis         return UnknownVal();
971fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
972fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
973fa0734ecSArgyrios Kyrtzidis       case BO_NE:
974fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
975fa0734ecSArgyrios Kyrtzidis       }
976fa0734ecSArgyrios Kyrtzidis     }
977fa0734ecSArgyrios Kyrtzidis 
9783563fde6SAnna Zaks     // If both values wrap regions, see if they're from different base regions.
9793563fde6SAnna Zaks     // Note, heap base symbolic regions are assumed to not alias with
9803563fde6SAnna Zaks     // each other; for example, we assume that malloc returns different address
9813563fde6SAnna Zaks     // on each invocation.
982aacc03c9SArtem Dergachev     // FIXME: ObjC object pointers always reside on the heap, but currently
983aacc03c9SArtem Dergachev     // we treat their memory space as unknown, because symbolic pointers
984aacc03c9SArtem Dergachev     // to ObjC objects may alias. There should be a way to construct
985aacc03c9SArtem Dergachev     // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
986aacc03c9SArtem Dergachev     // guesses memory space for ObjC object pointers manually instead of
987aacc03c9SArtem Dergachev     // relying on us.
9883563fde6SAnna Zaks     if (LeftBase != RightBase &&
9893563fde6SAnna Zaks         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
990a7dcc996SAnna Zaks          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
9919d96f843STed Kremenek       switch (op) {
9929d96f843STed Kremenek       default:
9933563fde6SAnna Zaks         return UnknownVal();
9949d96f843STed Kremenek       case BO_EQ:
9959d96f843STed Kremenek         return makeTruthVal(false, resultTy);
9969d96f843STed Kremenek       case BO_NE:
9979d96f843STed Kremenek         return makeTruthVal(true, resultTy);
9989d96f843STed Kremenek       }
9999d96f843STed Kremenek     }
1000fa0734ecSArgyrios Kyrtzidis 
1001bac964e1SAnna Zaks     // Handle special cases for when both regions are element regions.
1002fa0734ecSArgyrios Kyrtzidis     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
1003bac964e1SAnna Zaks     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
1004bac964e1SAnna Zaks     if (RightER && LeftER) {
1005fa0734ecSArgyrios Kyrtzidis       // Next, see if the two ERs have the same super-region and matching types.
1006fa0734ecSArgyrios Kyrtzidis       // FIXME: This should do something useful even if the types don't match,
1007fa0734ecSArgyrios Kyrtzidis       // though if both indexes are constant the RegionRawOffset path will
1008fa0734ecSArgyrios Kyrtzidis       // give the correct answer.
1009fa0734ecSArgyrios Kyrtzidis       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
1010fa0734ecSArgyrios Kyrtzidis           LeftER->getElementType() == RightER->getElementType()) {
1011fa0734ecSArgyrios Kyrtzidis         // Get the left index and cast it to the correct type.
1012fa0734ecSArgyrios Kyrtzidis         // If the index is unknown or undefined, bail out here.
1013fa0734ecSArgyrios Kyrtzidis         SVal LeftIndexVal = LeftER->getIndex();
101405785d16SDavid Blaikie         Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
1015fa0734ecSArgyrios Kyrtzidis         if (!LeftIndex)
1016fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
10172317f30fSTed Kremenek         LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
10182fdacbc5SDavid Blaikie         LeftIndex = LeftIndexVal.getAs<NonLoc>();
1019fa0734ecSArgyrios Kyrtzidis         if (!LeftIndex)
1020fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
1021fa0734ecSArgyrios Kyrtzidis 
1022fa0734ecSArgyrios Kyrtzidis         // Do the same for the right index.
1023fa0734ecSArgyrios Kyrtzidis         SVal RightIndexVal = RightER->getIndex();
102405785d16SDavid Blaikie         Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
1025fa0734ecSArgyrios Kyrtzidis         if (!RightIndex)
1026fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
10272317f30fSTed Kremenek         RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
10282fdacbc5SDavid Blaikie         RightIndex = RightIndexVal.getAs<NonLoc>();
1029fa0734ecSArgyrios Kyrtzidis         if (!RightIndex)
1030fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
1031fa0734ecSArgyrios Kyrtzidis 
1032fa0734ecSArgyrios Kyrtzidis         // Actually perform the operation.
1033fa0734ecSArgyrios Kyrtzidis         // evalBinOpNN expects the two indexes to already be the right type.
1034fa0734ecSArgyrios Kyrtzidis         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
1035fa0734ecSArgyrios Kyrtzidis       }
1036bac964e1SAnna Zaks     }
1037fa0734ecSArgyrios Kyrtzidis 
1038bac964e1SAnna Zaks     // Special handling of the FieldRegions, even with symbolic offsets.
1039bac964e1SAnna Zaks     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
1040bac964e1SAnna Zaks     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
1041bac964e1SAnna Zaks     if (RightFR && LeftFR) {
1042bac964e1SAnna Zaks       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
1043bac964e1SAnna Zaks                                                *this);
1044bac964e1SAnna Zaks       if (!R.isUnknown())
1045bac964e1SAnna Zaks         return R;
1046bac964e1SAnna Zaks     }
1047bac964e1SAnna Zaks 
1048bac964e1SAnna Zaks     // Compare the regions using the raw offsets.
1049bac964e1SAnna Zaks     RegionOffset LeftOffset = LeftMR->getAsOffset();
1050bac964e1SAnna Zaks     RegionOffset RightOffset = RightMR->getAsOffset();
1051fa0734ecSArgyrios Kyrtzidis 
10520dbb783cSCraig Topper     if (LeftOffset.getRegion() != nullptr &&
1053bac964e1SAnna Zaks         LeftOffset.getRegion() == RightOffset.getRegion() &&
1054bac964e1SAnna Zaks         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
1055bac964e1SAnna Zaks       int64_t left = LeftOffset.getOffset();
1056bac964e1SAnna Zaks       int64_t right = RightOffset.getOffset();
1057fa0734ecSArgyrios Kyrtzidis 
1058fa0734ecSArgyrios Kyrtzidis       switch (op) {
1059fa0734ecSArgyrios Kyrtzidis         default:
1060fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
1061fa0734ecSArgyrios Kyrtzidis         case BO_LT:
1062fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left < right, resultTy);
1063fa0734ecSArgyrios Kyrtzidis         case BO_GT:
1064fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left > right, resultTy);
1065fa0734ecSArgyrios Kyrtzidis         case BO_LE:
1066fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left <= right, resultTy);
1067fa0734ecSArgyrios Kyrtzidis         case BO_GE:
1068fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left >= right, resultTy);
1069fa0734ecSArgyrios Kyrtzidis         case BO_EQ:
1070fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left == right, resultTy);
1071fa0734ecSArgyrios Kyrtzidis         case BO_NE:
1072fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left != right, resultTy);
1073fa0734ecSArgyrios Kyrtzidis       }
1074fa0734ecSArgyrios Kyrtzidis     }
1075fa0734ecSArgyrios Kyrtzidis 
10763b4c3ea2SJordan Rose     // At this point we're not going to get a good answer, but we can try
10773b4c3ea2SJordan Rose     // conjuring an expression instead.
10783b4c3ea2SJordan Rose     SymbolRef LHSSym = lhs.getAsLocSymbol();
10793b4c3ea2SJordan Rose     SymbolRef RHSSym = rhs.getAsLocSymbol();
10803b4c3ea2SJordan Rose     if (LHSSym && RHSSym)
10813b4c3ea2SJordan Rose       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
10823b4c3ea2SJordan Rose 
1083fa0734ecSArgyrios Kyrtzidis     // If we get here, we have no way of comparing the regions.
1084fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
1085fa0734ecSArgyrios Kyrtzidis   }
1086fa0734ecSArgyrios Kyrtzidis   }
1087fa0734ecSArgyrios Kyrtzidis }
1088fa0734ecSArgyrios Kyrtzidis 
108949b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
1090fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
1091fa0734ecSArgyrios Kyrtzidis                                   Loc lhs, NonLoc rhs, QualType resultTy) {
109264c01f7bSDevin Coughlin   if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
109364c01f7bSDevin Coughlin     if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
109464c01f7bSDevin Coughlin       if (PTMSV->isNullMemberPointer())
109564c01f7bSDevin Coughlin         return UndefinedVal();
109664c01f7bSDevin Coughlin       if (const FieldDecl *FD = PTMSV->getDeclAs<FieldDecl>()) {
109764c01f7bSDevin Coughlin         SVal Result = lhs;
109864c01f7bSDevin Coughlin 
109964c01f7bSDevin Coughlin         for (const auto &I : *PTMSV)
110064c01f7bSDevin Coughlin           Result = StateMgr.getStoreManager().evalDerivedToBase(
110164c01f7bSDevin Coughlin               Result, I->getType(),I->isVirtual());
110264c01f7bSDevin Coughlin         return state->getLValue(FD, Result);
110364c01f7bSDevin Coughlin       }
110464c01f7bSDevin Coughlin     }
110564c01f7bSDevin Coughlin 
110664c01f7bSDevin Coughlin     return rhs;
110764c01f7bSDevin Coughlin   }
110864c01f7bSDevin Coughlin 
1109686df322SJordan Rose   assert(!BinaryOperator::isComparisonOp(op) &&
1110686df322SJordan Rose          "arguments to comparison ops must be of the same type");
1111fa0734ecSArgyrios Kyrtzidis 
1112fa0734ecSArgyrios Kyrtzidis   // Special case: rhs is a zero constant.
1113fa0734ecSArgyrios Kyrtzidis   if (rhs.isZeroConstant())
1114fa0734ecSArgyrios Kyrtzidis     return lhs;
1115fa0734ecSArgyrios Kyrtzidis 
111621524676SGabor Horvath   // Perserve the null pointer so that it can be found by the DerefChecker.
111721524676SGabor Horvath   if (lhs.isZeroConstant())
111821524676SGabor Horvath     return lhs;
111921524676SGabor Horvath 
1120fa0734ecSArgyrios Kyrtzidis   // We are dealing with pointer arithmetic.
1121fa0734ecSArgyrios Kyrtzidis 
1122fa0734ecSArgyrios Kyrtzidis   // Handle pointer arithmetic on constant values.
112305785d16SDavid Blaikie   if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
112405785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
1125fa0734ecSArgyrios Kyrtzidis       const llvm::APSInt &leftI = lhsInt->getValue();
1126fa0734ecSArgyrios Kyrtzidis       assert(leftI.isUnsigned());
1127fa0734ecSArgyrios Kyrtzidis       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1128fa0734ecSArgyrios Kyrtzidis 
1129fa0734ecSArgyrios Kyrtzidis       // Convert the bitwidth of rightI.  This should deal with overflow
1130fa0734ecSArgyrios Kyrtzidis       // since we are dealing with concrete values.
1131fa0734ecSArgyrios Kyrtzidis       rightI = rightI.extOrTrunc(leftI.getBitWidth());
1132fa0734ecSArgyrios Kyrtzidis 
1133fa0734ecSArgyrios Kyrtzidis       // Offset the increment by the pointer size.
1134fa0734ecSArgyrios Kyrtzidis       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
113521524676SGabor Horvath       QualType pointeeType = resultTy->getPointeeType();
113621524676SGabor Horvath       Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1137fa0734ecSArgyrios Kyrtzidis       rightI *= Multiplicand;
1138fa0734ecSArgyrios Kyrtzidis 
1139fa0734ecSArgyrios Kyrtzidis       // Compute the adjusted pointer.
1140fa0734ecSArgyrios Kyrtzidis       switch (op) {
1141fa0734ecSArgyrios Kyrtzidis         case BO_Add:
1142fa0734ecSArgyrios Kyrtzidis           rightI = leftI + rightI;
1143fa0734ecSArgyrios Kyrtzidis           break;
1144fa0734ecSArgyrios Kyrtzidis         case BO_Sub:
1145fa0734ecSArgyrios Kyrtzidis           rightI = leftI - rightI;
1146fa0734ecSArgyrios Kyrtzidis           break;
1147fa0734ecSArgyrios Kyrtzidis         default:
1148fa0734ecSArgyrios Kyrtzidis           llvm_unreachable("Invalid pointer arithmetic operation");
1149fa0734ecSArgyrios Kyrtzidis       }
1150fa0734ecSArgyrios Kyrtzidis       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1151fa0734ecSArgyrios Kyrtzidis     }
1152fa0734ecSArgyrios Kyrtzidis   }
1153fa0734ecSArgyrios Kyrtzidis 
1154fa0734ecSArgyrios Kyrtzidis   // Handle cases where 'lhs' is a region.
1155fa0734ecSArgyrios Kyrtzidis   if (const MemRegion *region = lhs.getAsRegion()) {
11562fdacbc5SDavid Blaikie     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1157fa0734ecSArgyrios Kyrtzidis     SVal index = UnknownVal();
11586dd11048SArtem Dergachev     const SubRegion *superR = nullptr;
11597333a9eaSArtem Dergachev     // We need to know the type of the pointer in order to add an integer to it.
11607333a9eaSArtem Dergachev     // Depending on the type, different amount of bytes is added.
1161fa0734ecSArgyrios Kyrtzidis     QualType elementType;
1162fa0734ecSArgyrios Kyrtzidis 
1163fa0734ecSArgyrios Kyrtzidis     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
116457a4a152STed Kremenek       assert(op == BO_Add || op == BO_Sub);
116557a4a152STed Kremenek       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1166fa0734ecSArgyrios Kyrtzidis                           getArrayIndexType());
11676dd11048SArtem Dergachev       superR = cast<SubRegion>(elemReg->getSuperRegion());
1168fa0734ecSArgyrios Kyrtzidis       elementType = elemReg->getElementType();
1169fa0734ecSArgyrios Kyrtzidis     }
1170fa0734ecSArgyrios Kyrtzidis     else if (isa<SubRegion>(region)) {
1171c4b28a8fSGabor Horvath       assert(op == BO_Add || op == BO_Sub);
1172c4b28a8fSGabor Horvath       index = (op == BO_Add) ? rhs : evalMinus(rhs);
11736dd11048SArtem Dergachev       superR = cast<SubRegion>(region);
11747333a9eaSArtem Dergachev       // TODO: Is this actually reliable? Maybe improving our MemRegion
11757333a9eaSArtem Dergachev       // hierarchy to provide typed regions for all non-void pointers would be
11767333a9eaSArtem Dergachev       // better. For instance, we cannot extend this towards LocAsInteger
11777333a9eaSArtem Dergachev       // operations, where result type of the expression is integer.
1178d1a08b6eSJordan Rose       if (resultTy->isAnyPointerType())
1179d1a08b6eSJordan Rose         elementType = resultTy->getPointeeType();
1180fa0734ecSArgyrios Kyrtzidis     }
1181fa0734ecSArgyrios Kyrtzidis 
1182df1bb8a6SArtem Dergachev     // Represent arithmetic on void pointers as arithmetic on char pointers.
1183df1bb8a6SArtem Dergachev     // It is fine when a TypedValueRegion of char value type represents
1184df1bb8a6SArtem Dergachev     // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1185df1bb8a6SArtem Dergachev     if (elementType->isVoidType())
1186df1bb8a6SArtem Dergachev       elementType = getContext().CharTy;
1187df1bb8a6SArtem Dergachev 
118805785d16SDavid Blaikie     if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1189fa0734ecSArgyrios Kyrtzidis       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1190fa0734ecSArgyrios Kyrtzidis                                                        superR, getContext()));
1191fa0734ecSArgyrios Kyrtzidis     }
1192fa0734ecSArgyrios Kyrtzidis   }
1193fa0734ecSArgyrios Kyrtzidis   return UnknownVal();
1194fa0734ecSArgyrios Kyrtzidis }
1195fa0734ecSArgyrios Kyrtzidis 
119649b1e38eSTed Kremenek const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1197fa0734ecSArgyrios Kyrtzidis                                                    SVal V) {
1198fa0734ecSArgyrios Kyrtzidis   if (V.isUnknownOrUndef())
11990dbb783cSCraig Topper     return nullptr;
1200fa0734ecSArgyrios Kyrtzidis 
120105785d16SDavid Blaikie   if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1202fa0734ecSArgyrios Kyrtzidis     return &X->getValue();
1203fa0734ecSArgyrios Kyrtzidis 
120405785d16SDavid Blaikie   if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1205fa0734ecSArgyrios Kyrtzidis     return &X->getValue();
1206fa0734ecSArgyrios Kyrtzidis 
1207fa0734ecSArgyrios Kyrtzidis   if (SymbolRef Sym = V.getAsSymbol())
1208244e1d7dSTed Kremenek     return state->getConstraintManager().getSymVal(state, Sym);
1209fa0734ecSArgyrios Kyrtzidis 
1210c0402c69SDominic Chen   // FIXME: Add support for SymExprs.
12110dbb783cSCraig Topper   return nullptr;
1212fa0734ecSArgyrios Kyrtzidis }
121312294f8dSArtem Dergachev 
121412294f8dSArtem Dergachev SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
121512294f8dSArtem Dergachev   // For now, this function tries to constant-fold symbols inside a
121612294f8dSArtem Dergachev   // nonloc::SymbolVal, and does nothing else. More simplifications should
121712294f8dSArtem Dergachev   // be possible, such as constant-folding an index in an ElementRegion.
121812294f8dSArtem Dergachev 
121912294f8dSArtem Dergachev   class Simplifier : public FullSValVisitor<Simplifier, SVal> {
122012294f8dSArtem Dergachev     ProgramStateRef State;
122112294f8dSArtem Dergachev     SValBuilder &SVB;
122212294f8dSArtem Dergachev 
122312294f8dSArtem Dergachev   public:
122412294f8dSArtem Dergachev     Simplifier(ProgramStateRef State)
122512294f8dSArtem Dergachev         : State(State), SVB(State->getStateManager().getSValBuilder()) {}
122612294f8dSArtem Dergachev 
122712294f8dSArtem Dergachev     SVal VisitSymbolData(const SymbolData *S) {
122812294f8dSArtem Dergachev       if (const llvm::APSInt *I =
122912294f8dSArtem Dergachev               SVB.getKnownValue(State, nonloc::SymbolVal(S)))
123012294f8dSArtem Dergachev         return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
123112294f8dSArtem Dergachev                                             : (SVal)SVB.makeIntVal(*I);
1232901d6156SAlexander Shaposhnikov       return Loc::isLocType(S->getType()) ? (SVal)SVB.makeLoc(S)
1233901d6156SAlexander Shaposhnikov                                           : nonloc::SymbolVal(S);
123412294f8dSArtem Dergachev     }
123512294f8dSArtem Dergachev 
1236c0402c69SDominic Chen     // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
1237c0402c69SDominic Chen     // start producing them.
123812294f8dSArtem Dergachev 
123912294f8dSArtem Dergachev     SVal VisitSymIntExpr(const SymIntExpr *S) {
124012294f8dSArtem Dergachev       SVal LHS = Visit(S->getLHS());
124112294f8dSArtem Dergachev       SVal RHS;
124212294f8dSArtem Dergachev       // By looking at the APSInt in the right-hand side of S, we cannot
124312294f8dSArtem Dergachev       // figure out if it should be treated as a Loc or as a NonLoc.
124412294f8dSArtem Dergachev       // So make our guess by recalling that we cannot multiply pointers
124512294f8dSArtem Dergachev       // or compare a pointer to an integer.
124612294f8dSArtem Dergachev       if (Loc::isLocType(S->getLHS()->getType()) &&
124712294f8dSArtem Dergachev           BinaryOperator::isComparisonOp(S->getOpcode())) {
124812294f8dSArtem Dergachev         // The usual conversion of $sym to &SymRegion{$sym}, as they have
124912294f8dSArtem Dergachev         // the same meaning for Loc-type symbols, but the latter form
125012294f8dSArtem Dergachev         // is preferred in SVal computations for being Loc itself.
125112294f8dSArtem Dergachev         if (SymbolRef Sym = LHS.getAsSymbol()) {
125212294f8dSArtem Dergachev           assert(Loc::isLocType(Sym->getType()));
125312294f8dSArtem Dergachev           LHS = SVB.makeLoc(Sym);
125412294f8dSArtem Dergachev         }
125512294f8dSArtem Dergachev         RHS = SVB.makeIntLocVal(S->getRHS());
125612294f8dSArtem Dergachev       } else {
125712294f8dSArtem Dergachev         RHS = SVB.makeIntVal(S->getRHS());
125812294f8dSArtem Dergachev       }
125912294f8dSArtem Dergachev       return SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType());
126012294f8dSArtem Dergachev     }
126112294f8dSArtem Dergachev 
126212294f8dSArtem Dergachev     SVal VisitSymSymExpr(const SymSymExpr *S) {
126312294f8dSArtem Dergachev       SVal LHS = Visit(S->getLHS());
126412294f8dSArtem Dergachev       SVal RHS = Visit(S->getRHS());
126512294f8dSArtem Dergachev       return SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType());
126612294f8dSArtem Dergachev     }
126712294f8dSArtem Dergachev 
126812294f8dSArtem Dergachev     SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
126912294f8dSArtem Dergachev 
127012294f8dSArtem Dergachev     SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
127112294f8dSArtem Dergachev 
127212294f8dSArtem Dergachev     SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
127312294f8dSArtem Dergachev       // Simplification is much more costly than computing complexity.
127412294f8dSArtem Dergachev       // For high complexity, it may be not worth it.
1275c0402c69SDominic Chen       if (V.getSymbol()->computeComplexity() > 100)
127612294f8dSArtem Dergachev         return V;
127712294f8dSArtem Dergachev       return Visit(V.getSymbol());
127812294f8dSArtem Dergachev     }
127912294f8dSArtem Dergachev 
128012294f8dSArtem Dergachev     SVal VisitSVal(SVal V) { return V; }
128112294f8dSArtem Dergachev   };
128212294f8dSArtem Dergachev 
128312294f8dSArtem Dergachev   return Simplifier(State).Visit(V);
128412294f8dSArtem Dergachev }
1285