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