1 // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.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 protected:
25   SVal dispatchCast(SVal val, QualType castTy) override;
26   SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
27   SVal evalCastFromLoc(Loc val, QualType castTy) override;
28 
29 public:
30   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
31                     ProgramStateManager &stateMgr)
32                     : SValBuilder(alloc, context, stateMgr) {}
33   ~SimpleSValBuilder() override {}
34 
35   SVal evalMinus(NonLoc val) override;
36   SVal evalComplement(NonLoc val) override;
37   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
38                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
39   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
40                    Loc lhs, Loc rhs, QualType resultTy) override;
41   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
42                    Loc lhs, NonLoc rhs, QualType resultTy) override;
43 
44   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
45   ///  (integer) value, that value is returned. Otherwise, returns NULL.
46   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
47 
48   /// Recursively descends into symbolic expressions and replaces symbols
49   /// with their known values (in the sense of the getKnownValue() method).
50   SVal simplifySVal(ProgramStateRef State, SVal V) override;
51 
52   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
53                      const llvm::APSInt &RHS, QualType resultTy);
54 };
55 } // end anonymous namespace
56 
57 SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
58                                            ASTContext &context,
59                                            ProgramStateManager &stateMgr) {
60   return new SimpleSValBuilder(alloc, context, stateMgr);
61 }
62 
63 //===----------------------------------------------------------------------===//
64 // Transfer function for Casts.
65 //===----------------------------------------------------------------------===//
66 
67 SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
68   assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
69   return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
70                            : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
71 }
72 
73 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
74 
75   bool isLocType = Loc::isLocType(castTy);
76 
77   if (val.getAs<nonloc::PointerToMember>())
78     return val;
79 
80   if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
81     if (isLocType)
82       return LI->getLoc();
83 
84     // FIXME: Correctly support promotions/truncations.
85     unsigned castSize = Context.getTypeSize(castTy);
86     if (castSize == LI->getNumBits())
87       return val;
88     return makeLocAsInteger(LI->getLoc(), castSize);
89   }
90 
91   if (const SymExpr *se = val.getAsSymbolicExpression()) {
92     QualType T = Context.getCanonicalType(se->getType());
93     // If types are the same or both are integers, ignore the cast.
94     // FIXME: Remove this hack when we support symbolic truncation/extension.
95     // HACK: If both castTy and T are integers, ignore the cast.  This is
96     // not a permanent solution.  Eventually we want to precisely handle
97     // extension/truncation of symbolic integers.  This prevents us from losing
98     // precision when we assign 'x = y' and 'y' is symbolic and x and y are
99     // different integer types.
100    if (haveSameType(T, castTy))
101       return val;
102 
103     if (!isLocType)
104       return makeNonLoc(se, T, castTy);
105     return UnknownVal();
106   }
107 
108   // If value is a non-integer constant, produce unknown.
109   if (!val.getAs<nonloc::ConcreteInt>())
110     return UnknownVal();
111 
112   // Handle casts to a boolean type.
113   if (castTy->isBooleanType()) {
114     bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
115     return makeTruthVal(b, castTy);
116   }
117 
118   // Only handle casts from integers to integers - if val is an integer constant
119   // being cast to a non-integer type, produce unknown.
120   if (!isLocType && !castTy->isIntegralOrEnumerationType())
121     return UnknownVal();
122 
123   llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
124   BasicVals.getAPSIntType(castTy).apply(i);
125 
126   if (isLocType)
127     return makeIntLocVal(i);
128   else
129     return makeIntVal(i);
130 }
131 
132 SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
133 
134   // Casts from pointers -> pointers, just return the lval.
135   //
136   // Casts from pointers -> references, just return the lval.  These
137   //   can be introduced by the frontend for corner cases, e.g
138   //   casting from va_list* to __builtin_va_list&.
139   //
140   if (Loc::isLocType(castTy) || castTy->isReferenceType())
141     return val;
142 
143   // FIXME: Handle transparent unions where a value can be "transparently"
144   //  lifted into a union type.
145   if (castTy->isUnionType())
146     return UnknownVal();
147 
148   // Casting a Loc to a bool will almost always be true,
149   // unless this is a weak function or a symbolic region.
150   if (castTy->isBooleanType()) {
151     switch (val.getSubKind()) {
152       case loc::MemRegionValKind: {
153         const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
154         if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
155           if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
156             if (FD->isWeak())
157               // FIXME: Currently we are using an extent symbol here,
158               // because there are no generic region address metadata
159               // symbols to use, only content metadata.
160               return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
161 
162         if (const SymbolicRegion *SymR = R->getSymbolicBase())
163           return nonloc::SymbolVal(SymR->getSymbol());
164 
165         // FALL-THROUGH
166         LLVM_FALLTHROUGH;
167       }
168 
169       case loc::GotoLabelKind:
170         // Labels and non-symbolic memory regions are always true.
171         return makeTruthVal(true, castTy);
172     }
173   }
174 
175   if (castTy->isIntegralOrEnumerationType()) {
176     unsigned BitWidth = Context.getTypeSize(castTy);
177 
178     if (!val.getAs<loc::ConcreteInt>())
179       return makeLocAsInteger(val, BitWidth);
180 
181     llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
182     BasicVals.getAPSIntType(castTy).apply(i);
183     return makeIntVal(i);
184   }
185 
186   // All other cases: return 'UnknownVal'.  This includes casting pointers
187   // to floats, which is probably badness it itself, but this is a good
188   // intermediate solution until we do something better.
189   return UnknownVal();
190 }
191 
192 //===----------------------------------------------------------------------===//
193 // Transfer function for unary operators.
194 //===----------------------------------------------------------------------===//
195 
196 SVal SimpleSValBuilder::evalMinus(NonLoc val) {
197   switch (val.getSubKind()) {
198   case nonloc::ConcreteIntKind:
199     return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
200   default:
201     return UnknownVal();
202   }
203 }
204 
205 SVal SimpleSValBuilder::evalComplement(NonLoc X) {
206   switch (X.getSubKind()) {
207   case nonloc::ConcreteIntKind:
208     return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
209   default:
210     return UnknownVal();
211   }
212 }
213 
214 //===----------------------------------------------------------------------===//
215 // Transfer function for binary operators.
216 //===----------------------------------------------------------------------===//
217 
218 SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
219                                     BinaryOperator::Opcode op,
220                                     const llvm::APSInt &RHS,
221                                     QualType resultTy) {
222   bool isIdempotent = false;
223 
224   // Check for a few special cases with known reductions first.
225   switch (op) {
226   default:
227     // We can't reduce this case; just treat it normally.
228     break;
229   case BO_Mul:
230     // a*0 and a*1
231     if (RHS == 0)
232       return makeIntVal(0, resultTy);
233     else if (RHS == 1)
234       isIdempotent = true;
235     break;
236   case BO_Div:
237     // a/0 and a/1
238     if (RHS == 0)
239       // This is also handled elsewhere.
240       return UndefinedVal();
241     else if (RHS == 1)
242       isIdempotent = true;
243     break;
244   case BO_Rem:
245     // a%0 and a%1
246     if (RHS == 0)
247       // This is also handled elsewhere.
248       return UndefinedVal();
249     else if (RHS == 1)
250       return makeIntVal(0, resultTy);
251     break;
252   case BO_Add:
253   case BO_Sub:
254   case BO_Shl:
255   case BO_Shr:
256   case BO_Xor:
257     // a+0, a-0, a<<0, a>>0, a^0
258     if (RHS == 0)
259       isIdempotent = true;
260     break;
261   case BO_And:
262     // a&0 and a&(~0)
263     if (RHS == 0)
264       return makeIntVal(0, resultTy);
265     else if (RHS.isAllOnesValue())
266       isIdempotent = true;
267     break;
268   case BO_Or:
269     // a|0 and a|(~0)
270     if (RHS == 0)
271       isIdempotent = true;
272     else if (RHS.isAllOnesValue()) {
273       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
274       return nonloc::ConcreteInt(Result);
275     }
276     break;
277   }
278 
279   // Idempotent ops (like a*1) can still change the type of an expression.
280   // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
281   // dirty work.
282   if (isIdempotent)
283       return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
284 
285   // If we reach this point, the expression cannot be simplified.
286   // Make a SymbolVal for the entire expression, after converting the RHS.
287   const llvm::APSInt *ConvertedRHS = &RHS;
288   if (BinaryOperator::isComparisonOp(op)) {
289     // We're looking for a type big enough to compare the symbolic value
290     // with the given constant.
291     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
292     ASTContext &Ctx = getContext();
293     QualType SymbolType = LHS->getType();
294     uint64_t ValWidth = RHS.getBitWidth();
295     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
296 
297     if (ValWidth < TypeWidth) {
298       // If the value is too small, extend it.
299       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
300     } else if (ValWidth == TypeWidth) {
301       // If the value is signed but the symbol is unsigned, do the comparison
302       // in unsigned space. [C99 6.3.1.8]
303       // (For the opposite case, the value is already unsigned.)
304       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
305         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
306     }
307   } else
308     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
309 
310   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
311 }
312 
313 SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
314                                   BinaryOperator::Opcode op,
315                                   NonLoc lhs, NonLoc rhs,
316                                   QualType resultTy)  {
317   NonLoc InputLHS = lhs;
318   NonLoc InputRHS = rhs;
319 
320   // Handle trivial case where left-side and right-side are the same.
321   if (lhs == rhs)
322     switch (op) {
323       default:
324         break;
325       case BO_EQ:
326       case BO_LE:
327       case BO_GE:
328         return makeTruthVal(true, resultTy);
329       case BO_LT:
330       case BO_GT:
331       case BO_NE:
332         return makeTruthVal(false, resultTy);
333       case BO_Xor:
334       case BO_Sub:
335         if (resultTy->isIntegralOrEnumerationType())
336           return makeIntVal(0, resultTy);
337         return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
338       case BO_Or:
339       case BO_And:
340         return evalCastFromNonLoc(lhs, resultTy);
341     }
342 
343   while (1) {
344     switch (lhs.getSubKind()) {
345     default:
346       return makeSymExprValNN(state, op, lhs, rhs, resultTy);
347     case nonloc::PointerToMemberKind: {
348       assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
349              "Both SVals should have pointer-to-member-type");
350       auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
351            RPTM = rhs.castAs<nonloc::PointerToMember>();
352       auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
353       switch (op) {
354         case BO_EQ:
355           return makeTruthVal(LPTMD == RPTMD, resultTy);
356         case BO_NE:
357           return makeTruthVal(LPTMD != RPTMD, resultTy);
358         default:
359           return UnknownVal();
360       }
361     }
362     case nonloc::LocAsIntegerKind: {
363       Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
364       switch (rhs.getSubKind()) {
365         case nonloc::LocAsIntegerKind:
366           return evalBinOpLL(state, op, lhsL,
367                              rhs.castAs<nonloc::LocAsInteger>().getLoc(),
368                              resultTy);
369         case nonloc::ConcreteIntKind: {
370           // Transform the integer into a location and compare.
371           // FIXME: This only makes sense for comparisons. If we want to, say,
372           // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
373           // then pack it back into a LocAsInteger.
374           llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
375           BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
376           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
377         }
378         default:
379           switch (op) {
380             case BO_EQ:
381               return makeTruthVal(false, resultTy);
382             case BO_NE:
383               return makeTruthVal(true, resultTy);
384             default:
385               // This case also handles pointer arithmetic.
386               return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
387           }
388       }
389     }
390     case nonloc::ConcreteIntKind: {
391       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
392 
393       // If we're dealing with two known constants, just perform the operation.
394       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
395         llvm::APSInt RHSValue = *KnownRHSValue;
396         if (BinaryOperator::isComparisonOp(op)) {
397           // We're looking for a type big enough to compare the two values.
398           // FIXME: This is not correct. char + short will result in a promotion
399           // to int. Unfortunately we have lost types by this point.
400           APSIntType CompareType = std::max(APSIntType(LHSValue),
401                                             APSIntType(RHSValue));
402           CompareType.apply(LHSValue);
403           CompareType.apply(RHSValue);
404         } else if (!BinaryOperator::isShiftOp(op)) {
405           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
406           IntType.apply(LHSValue);
407           IntType.apply(RHSValue);
408         }
409 
410         const llvm::APSInt *Result =
411           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
412         if (!Result)
413           return UndefinedVal();
414 
415         return nonloc::ConcreteInt(*Result);
416       }
417 
418       // Swap the left and right sides and flip the operator if doing so
419       // allows us to better reason about the expression (this is a form
420       // of expression canonicalization).
421       // While we're at it, catch some special cases for non-commutative ops.
422       switch (op) {
423       case BO_LT:
424       case BO_GT:
425       case BO_LE:
426       case BO_GE:
427         op = BinaryOperator::reverseComparisonOp(op);
428         // FALL-THROUGH
429       case BO_EQ:
430       case BO_NE:
431       case BO_Add:
432       case BO_Mul:
433       case BO_And:
434       case BO_Xor:
435       case BO_Or:
436         std::swap(lhs, rhs);
437         continue;
438       case BO_Shr:
439         // (~0)>>a
440         if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
441           return evalCastFromNonLoc(lhs, resultTy);
442         // FALL-THROUGH
443       case BO_Shl:
444         // 0<<a and 0>>a
445         if (LHSValue == 0)
446           return evalCastFromNonLoc(lhs, resultTy);
447         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
448       default:
449         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
450       }
451     }
452     case nonloc::SymbolValKind: {
453       // We only handle LHS as simple symbols or SymIntExprs.
454       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
455 
456       // LHS is a symbolic expression.
457       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
458 
459         // Is this a logical not? (!x is represented as x == 0.)
460         if (op == BO_EQ && rhs.isZeroConstant()) {
461           // We know how to negate certain expressions. Simplify them here.
462 
463           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
464           switch (opc) {
465           default:
466             // We don't know how to negate this operation.
467             // Just handle it as if it were a normal comparison to 0.
468             break;
469           case BO_LAnd:
470           case BO_LOr:
471             llvm_unreachable("Logical operators handled by branching logic.");
472           case BO_Assign:
473           case BO_MulAssign:
474           case BO_DivAssign:
475           case BO_RemAssign:
476           case BO_AddAssign:
477           case BO_SubAssign:
478           case BO_ShlAssign:
479           case BO_ShrAssign:
480           case BO_AndAssign:
481           case BO_XorAssign:
482           case BO_OrAssign:
483           case BO_Comma:
484             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
485           case BO_PtrMemD:
486           case BO_PtrMemI:
487             llvm_unreachable("Pointer arithmetic not handled here.");
488           case BO_LT:
489           case BO_GT:
490           case BO_LE:
491           case BO_GE:
492           case BO_EQ:
493           case BO_NE:
494             assert(resultTy->isBooleanType() ||
495                    resultTy == getConditionType());
496             assert(symIntExpr->getType()->isBooleanType() ||
497                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
498                                                        getConditionType()));
499             // Negate the comparison and make a value.
500             opc = BinaryOperator::negateComparisonOp(opc);
501             return makeNonLoc(symIntExpr->getLHS(), opc,
502                 symIntExpr->getRHS(), resultTy);
503           }
504         }
505 
506         // For now, only handle expressions whose RHS is a constant.
507         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
508           // If both the LHS and the current expression are additive,
509           // fold their constants and try again.
510           if (BinaryOperator::isAdditiveOp(op)) {
511             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
512             if (BinaryOperator::isAdditiveOp(lop)) {
513               // Convert the two constants to a common type, then combine them.
514 
515               // resultTy may not be the best type to convert to, but it's
516               // probably the best choice in expressions with mixed type
517               // (such as x+1U+2LL). The rules for implicit conversions should
518               // choose a reasonable type to preserve the expression, and will
519               // at least match how the value is going to be used.
520               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
521               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
522               const llvm::APSInt &second = IntType.convert(*RHSValue);
523 
524               const llvm::APSInt *newRHS;
525               if (lop == op)
526                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
527               else
528                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
529 
530               assert(newRHS && "Invalid operation despite common type!");
531               rhs = nonloc::ConcreteInt(*newRHS);
532               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
533               op = lop;
534               continue;
535             }
536           }
537 
538           // Otherwise, make a SymIntExpr out of the expression.
539           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
540         }
541       }
542 
543       // Does the symbolic expression simplify to a constant?
544       // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
545       // and try again.
546       SVal simplifiedLhs = simplifySVal(state, lhs);
547       if (simplifiedLhs != lhs)
548         if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
549           lhs = *simplifiedLhsAsNonLoc;
550           continue;
551         }
552 
553       // Is the RHS a constant?
554       if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
555         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
556 
557       // Give up -- this is not a symbolic expression we can handle.
558       return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
559     }
560     }
561   }
562 }
563 
564 static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
565                                             const FieldRegion *RightFR,
566                                             BinaryOperator::Opcode op,
567                                             QualType resultTy,
568                                             SimpleSValBuilder &SVB) {
569   // Only comparisons are meaningful here!
570   if (!BinaryOperator::isComparisonOp(op))
571     return UnknownVal();
572 
573   // Next, see if the two FRs have the same super-region.
574   // FIXME: This doesn't handle casts yet, and simply stripping the casts
575   // doesn't help.
576   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
577     return UnknownVal();
578 
579   const FieldDecl *LeftFD = LeftFR->getDecl();
580   const FieldDecl *RightFD = RightFR->getDecl();
581   const RecordDecl *RD = LeftFD->getParent();
582 
583   // Make sure the two FRs are from the same kind of record. Just in case!
584   // FIXME: This is probably where inheritance would be a problem.
585   if (RD != RightFD->getParent())
586     return UnknownVal();
587 
588   // We know for sure that the two fields are not the same, since that
589   // would have given us the same SVal.
590   if (op == BO_EQ)
591     return SVB.makeTruthVal(false, resultTy);
592   if (op == BO_NE)
593     return SVB.makeTruthVal(true, resultTy);
594 
595   // Iterate through the fields and see which one comes first.
596   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
597   // members and the units in which bit-fields reside have addresses that
598   // increase in the order in which they are declared."
599   bool leftFirst = (op == BO_LT || op == BO_LE);
600   for (const auto *I : RD->fields()) {
601     if (I == LeftFD)
602       return SVB.makeTruthVal(leftFirst, resultTy);
603     if (I == RightFD)
604       return SVB.makeTruthVal(!leftFirst, resultTy);
605   }
606 
607   llvm_unreachable("Fields not found in parent record's definition");
608 }
609 
610 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
611 SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
612                                   BinaryOperator::Opcode op,
613                                   Loc lhs, Loc rhs,
614                                   QualType resultTy) {
615   // Only comparisons and subtractions are valid operations on two pointers.
616   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
617   // However, if a pointer is casted to an integer, evalBinOpNN may end up
618   // calling this function with another operation (PR7527). We don't attempt to
619   // model this for now, but it could be useful, particularly when the
620   // "location" is actually an integer value that's been passed through a void*.
621   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
622     return UnknownVal();
623 
624   // Special cases for when both sides are identical.
625   if (lhs == rhs) {
626     switch (op) {
627     default:
628       llvm_unreachable("Unimplemented operation for two identical values");
629     case BO_Sub:
630       return makeZeroVal(resultTy);
631     case BO_EQ:
632     case BO_LE:
633     case BO_GE:
634       return makeTruthVal(true, resultTy);
635     case BO_NE:
636     case BO_LT:
637     case BO_GT:
638       return makeTruthVal(false, resultTy);
639     }
640   }
641 
642   switch (lhs.getSubKind()) {
643   default:
644     llvm_unreachable("Ordering not implemented for this Loc.");
645 
646   case loc::GotoLabelKind:
647     // The only thing we know about labels is that they're non-null.
648     if (rhs.isZeroConstant()) {
649       switch (op) {
650       default:
651         break;
652       case BO_Sub:
653         return evalCastFromLoc(lhs, resultTy);
654       case BO_EQ:
655       case BO_LE:
656       case BO_LT:
657         return makeTruthVal(false, resultTy);
658       case BO_NE:
659       case BO_GT:
660       case BO_GE:
661         return makeTruthVal(true, resultTy);
662       }
663     }
664     // There may be two labels for the same location, and a function region may
665     // have the same address as a label at the start of the function (depending
666     // on the ABI).
667     // FIXME: we can probably do a comparison against other MemRegions, though.
668     // FIXME: is there a way to tell if two labels refer to the same location?
669     return UnknownVal();
670 
671   case loc::ConcreteIntKind: {
672     // If one of the operands is a symbol and the other is a constant,
673     // build an expression for use by the constraint manager.
674     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
675       // We can only build expressions with symbols on the left,
676       // so we need a reversible operator.
677       if (!BinaryOperator::isComparisonOp(op))
678         return UnknownVal();
679 
680       const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
681       op = BinaryOperator::reverseComparisonOp(op);
682       return makeNonLoc(rSym, op, lVal, resultTy);
683     }
684 
685     // If both operands are constants, just perform the operation.
686     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
687       SVal ResultVal =
688           lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
689       if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
690         return evalCastFromNonLoc(*Result, resultTy);
691 
692       assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
693       return UnknownVal();
694     }
695 
696     // Special case comparisons against NULL.
697     // This must come after the test if the RHS is a symbol, which is used to
698     // build constraints. The address of any non-symbolic region is guaranteed
699     // to be non-NULL, as is any label.
700     assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
701     if (lhs.isZeroConstant()) {
702       switch (op) {
703       default:
704         break;
705       case BO_EQ:
706       case BO_GT:
707       case BO_GE:
708         return makeTruthVal(false, resultTy);
709       case BO_NE:
710       case BO_LT:
711       case BO_LE:
712         return makeTruthVal(true, resultTy);
713       }
714     }
715 
716     // Comparing an arbitrary integer to a region or label address is
717     // completely unknowable.
718     return UnknownVal();
719   }
720   case loc::MemRegionValKind: {
721     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
722       // If one of the operands is a symbol and the other is a constant,
723       // build an expression for use by the constraint manager.
724       if (SymbolRef lSym = lhs.getAsLocSymbol(true))
725         return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
726 
727       // Special case comparisons to NULL.
728       // This must come after the test if the LHS is a symbol, which is used to
729       // build constraints. The address of any non-symbolic region is guaranteed
730       // to be non-NULL.
731       if (rInt->isZeroConstant()) {
732         if (op == BO_Sub)
733           return evalCastFromLoc(lhs, resultTy);
734 
735         if (BinaryOperator::isComparisonOp(op)) {
736           QualType boolType = getContext().BoolTy;
737           NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
738           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
739           return evalBinOpNN(state, op, l, r, resultTy);
740         }
741       }
742 
743       // Comparing a region to an arbitrary integer is completely unknowable.
744       return UnknownVal();
745     }
746 
747     // Get both values as regions, if possible.
748     const MemRegion *LeftMR = lhs.getAsRegion();
749     assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
750 
751     const MemRegion *RightMR = rhs.getAsRegion();
752     if (!RightMR)
753       // The RHS is probably a label, which in theory could address a region.
754       // FIXME: we can probably make a more useful statement about non-code
755       // regions, though.
756       return UnknownVal();
757 
758     const MemRegion *LeftBase = LeftMR->getBaseRegion();
759     const MemRegion *RightBase = RightMR->getBaseRegion();
760     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
761     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
762     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
763 
764     // If the two regions are from different known memory spaces they cannot be
765     // equal. Also, assume that no symbolic region (whose memory space is
766     // unknown) is on the stack.
767     if (LeftMS != RightMS &&
768         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
769          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
770       switch (op) {
771       default:
772         return UnknownVal();
773       case BO_EQ:
774         return makeTruthVal(false, resultTy);
775       case BO_NE:
776         return makeTruthVal(true, resultTy);
777       }
778     }
779 
780     // If both values wrap regions, see if they're from different base regions.
781     // Note, heap base symbolic regions are assumed to not alias with
782     // each other; for example, we assume that malloc returns different address
783     // on each invocation.
784     // FIXME: ObjC object pointers always reside on the heap, but currently
785     // we treat their memory space as unknown, because symbolic pointers
786     // to ObjC objects may alias. There should be a way to construct
787     // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
788     // guesses memory space for ObjC object pointers manually instead of
789     // relying on us.
790     if (LeftBase != RightBase &&
791         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
792          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
793       switch (op) {
794       default:
795         return UnknownVal();
796       case BO_EQ:
797         return makeTruthVal(false, resultTy);
798       case BO_NE:
799         return makeTruthVal(true, resultTy);
800       }
801     }
802 
803     // Handle special cases for when both regions are element regions.
804     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
805     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
806     if (RightER && LeftER) {
807       // Next, see if the two ERs have the same super-region and matching types.
808       // FIXME: This should do something useful even if the types don't match,
809       // though if both indexes are constant the RegionRawOffset path will
810       // give the correct answer.
811       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
812           LeftER->getElementType() == RightER->getElementType()) {
813         // Get the left index and cast it to the correct type.
814         // If the index is unknown or undefined, bail out here.
815         SVal LeftIndexVal = LeftER->getIndex();
816         Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
817         if (!LeftIndex)
818           return UnknownVal();
819         LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
820         LeftIndex = LeftIndexVal.getAs<NonLoc>();
821         if (!LeftIndex)
822           return UnknownVal();
823 
824         // Do the same for the right index.
825         SVal RightIndexVal = RightER->getIndex();
826         Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
827         if (!RightIndex)
828           return UnknownVal();
829         RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
830         RightIndex = RightIndexVal.getAs<NonLoc>();
831         if (!RightIndex)
832           return UnknownVal();
833 
834         // Actually perform the operation.
835         // evalBinOpNN expects the two indexes to already be the right type.
836         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
837       }
838     }
839 
840     // Special handling of the FieldRegions, even with symbolic offsets.
841     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
842     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
843     if (RightFR && LeftFR) {
844       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
845                                                *this);
846       if (!R.isUnknown())
847         return R;
848     }
849 
850     // Compare the regions using the raw offsets.
851     RegionOffset LeftOffset = LeftMR->getAsOffset();
852     RegionOffset RightOffset = RightMR->getAsOffset();
853 
854     if (LeftOffset.getRegion() != nullptr &&
855         LeftOffset.getRegion() == RightOffset.getRegion() &&
856         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
857       int64_t left = LeftOffset.getOffset();
858       int64_t right = RightOffset.getOffset();
859 
860       switch (op) {
861         default:
862           return UnknownVal();
863         case BO_LT:
864           return makeTruthVal(left < right, resultTy);
865         case BO_GT:
866           return makeTruthVal(left > right, resultTy);
867         case BO_LE:
868           return makeTruthVal(left <= right, resultTy);
869         case BO_GE:
870           return makeTruthVal(left >= right, resultTy);
871         case BO_EQ:
872           return makeTruthVal(left == right, resultTy);
873         case BO_NE:
874           return makeTruthVal(left != right, resultTy);
875       }
876     }
877 
878     // At this point we're not going to get a good answer, but we can try
879     // conjuring an expression instead.
880     SymbolRef LHSSym = lhs.getAsLocSymbol();
881     SymbolRef RHSSym = rhs.getAsLocSymbol();
882     if (LHSSym && RHSSym)
883       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
884 
885     // If we get here, we have no way of comparing the regions.
886     return UnknownVal();
887   }
888   }
889 }
890 
891 SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
892                                   BinaryOperator::Opcode op,
893                                   Loc lhs, NonLoc rhs, QualType resultTy) {
894   if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
895     if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
896       if (PTMSV->isNullMemberPointer())
897         return UndefinedVal();
898       if (const FieldDecl *FD = PTMSV->getDeclAs<FieldDecl>()) {
899         SVal Result = lhs;
900 
901         for (const auto &I : *PTMSV)
902           Result = StateMgr.getStoreManager().evalDerivedToBase(
903               Result, I->getType(),I->isVirtual());
904         return state->getLValue(FD, Result);
905       }
906     }
907 
908     return rhs;
909   }
910 
911   assert(!BinaryOperator::isComparisonOp(op) &&
912          "arguments to comparison ops must be of the same type");
913 
914   // Special case: rhs is a zero constant.
915   if (rhs.isZeroConstant())
916     return lhs;
917 
918   // We are dealing with pointer arithmetic.
919 
920   // Handle pointer arithmetic on constant values.
921   if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
922     if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
923       const llvm::APSInt &leftI = lhsInt->getValue();
924       assert(leftI.isUnsigned());
925       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
926 
927       // Convert the bitwidth of rightI.  This should deal with overflow
928       // since we are dealing with concrete values.
929       rightI = rightI.extOrTrunc(leftI.getBitWidth());
930 
931       // Offset the increment by the pointer size.
932       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
933       rightI *= Multiplicand;
934 
935       // Compute the adjusted pointer.
936       switch (op) {
937         case BO_Add:
938           rightI = leftI + rightI;
939           break;
940         case BO_Sub:
941           rightI = leftI - rightI;
942           break;
943         default:
944           llvm_unreachable("Invalid pointer arithmetic operation");
945       }
946       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
947     }
948   }
949 
950   // Handle cases where 'lhs' is a region.
951   if (const MemRegion *region = lhs.getAsRegion()) {
952     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
953     SVal index = UnknownVal();
954     const SubRegion *superR = nullptr;
955     // We need to know the type of the pointer in order to add an integer to it.
956     // Depending on the type, different amount of bytes is added.
957     QualType elementType;
958 
959     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
960       assert(op == BO_Add || op == BO_Sub);
961       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
962                           getArrayIndexType());
963       superR = cast<SubRegion>(elemReg->getSuperRegion());
964       elementType = elemReg->getElementType();
965     }
966     else if (isa<SubRegion>(region)) {
967       assert(op == BO_Add || op == BO_Sub);
968       index = (op == BO_Add) ? rhs : evalMinus(rhs);
969       superR = cast<SubRegion>(region);
970       // TODO: Is this actually reliable? Maybe improving our MemRegion
971       // hierarchy to provide typed regions for all non-void pointers would be
972       // better. For instance, we cannot extend this towards LocAsInteger
973       // operations, where result type of the expression is integer.
974       if (resultTy->isAnyPointerType())
975         elementType = resultTy->getPointeeType();
976     }
977 
978     if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
979       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
980                                                        superR, getContext()));
981     }
982   }
983   return UnknownVal();
984 }
985 
986 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
987                                                    SVal V) {
988   if (V.isUnknownOrUndef())
989     return nullptr;
990 
991   if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
992     return &X->getValue();
993 
994   if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
995     return &X->getValue();
996 
997   if (SymbolRef Sym = V.getAsSymbol())
998     return state->getConstraintManager().getSymVal(state, Sym);
999 
1000   // FIXME: Add support for SymExprs.
1001   return nullptr;
1002 }
1003 
1004 SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
1005   // For now, this function tries to constant-fold symbols inside a
1006   // nonloc::SymbolVal, and does nothing else. More simplifications should
1007   // be possible, such as constant-folding an index in an ElementRegion.
1008 
1009   class Simplifier : public FullSValVisitor<Simplifier, SVal> {
1010     ProgramStateRef State;
1011     SValBuilder &SVB;
1012 
1013   public:
1014     Simplifier(ProgramStateRef State)
1015         : State(State), SVB(State->getStateManager().getSValBuilder()) {}
1016 
1017     SVal VisitSymbolData(const SymbolData *S) {
1018       if (const llvm::APSInt *I =
1019               SVB.getKnownValue(State, nonloc::SymbolVal(S)))
1020         return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
1021                                             : (SVal)SVB.makeIntVal(*I);
1022       return nonloc::SymbolVal(S);
1023     }
1024 
1025     // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
1026     // start producing them.
1027 
1028     SVal VisitSymIntExpr(const SymIntExpr *S) {
1029       SVal LHS = Visit(S->getLHS());
1030       SVal RHS;
1031       // By looking at the APSInt in the right-hand side of S, we cannot
1032       // figure out if it should be treated as a Loc or as a NonLoc.
1033       // So make our guess by recalling that we cannot multiply pointers
1034       // or compare a pointer to an integer.
1035       if (Loc::isLocType(S->getLHS()->getType()) &&
1036           BinaryOperator::isComparisonOp(S->getOpcode())) {
1037         // The usual conversion of $sym to &SymRegion{$sym}, as they have
1038         // the same meaning for Loc-type symbols, but the latter form
1039         // is preferred in SVal computations for being Loc itself.
1040         if (SymbolRef Sym = LHS.getAsSymbol()) {
1041           assert(Loc::isLocType(Sym->getType()));
1042           LHS = SVB.makeLoc(Sym);
1043         }
1044         RHS = SVB.makeIntLocVal(S->getRHS());
1045       } else {
1046         RHS = SVB.makeIntVal(S->getRHS());
1047       }
1048       return SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType());
1049     }
1050 
1051     SVal VisitSymSymExpr(const SymSymExpr *S) {
1052       SVal LHS = Visit(S->getLHS());
1053       SVal RHS = Visit(S->getRHS());
1054       return SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType());
1055     }
1056 
1057     SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
1058 
1059     SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
1060 
1061     SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
1062       // Simplification is much more costly than computing complexity.
1063       // For high complexity, it may be not worth it.
1064       if (V.getSymbol()->computeComplexity() > 100)
1065         return V;
1066       return Visit(V.getSymbol());
1067     }
1068 
1069     SVal VisitSVal(SVal V) { return V; }
1070   };
1071 
1072   return Simplifier(State).Visit(V);
1073 }
1074