clang API Documentation

SimpleSValBuilder.cpp
Go to the documentation of this file.
00001 // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
00015 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
00016 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
00017 
00018 using namespace clang;
00019 using namespace ento;
00020 
00021 namespace {
00022 class SimpleSValBuilder : public SValBuilder {
00023 protected:
00024   SVal dispatchCast(SVal val, QualType castTy) override;
00025   SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
00026   SVal evalCastFromLoc(Loc val, QualType castTy) override;
00027 
00028 public:
00029   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
00030                     ProgramStateManager &stateMgr)
00031                     : SValBuilder(alloc, context, stateMgr) {}
00032   virtual ~SimpleSValBuilder() {}
00033 
00034   SVal evalMinus(NonLoc val) override;
00035   SVal evalComplement(NonLoc val) override;
00036   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
00037                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
00038   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
00039                    Loc lhs, Loc rhs, QualType resultTy) override;
00040   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
00041                    Loc lhs, NonLoc rhs, QualType resultTy) override;
00042 
00043   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
00044   ///  (integer) value, that value is returned. Otherwise, returns NULL.
00045   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
00046 
00047   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
00048                      const llvm::APSInt &RHS, QualType resultTy);
00049 };
00050 } // end anonymous namespace
00051 
00052 SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
00053                                            ASTContext &context,
00054                                            ProgramStateManager &stateMgr) {
00055   return new SimpleSValBuilder(alloc, context, stateMgr);
00056 }
00057 
00058 //===----------------------------------------------------------------------===//
00059 // Transfer function for Casts.
00060 //===----------------------------------------------------------------------===//
00061 
00062 SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
00063   assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
00064   return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
00065                            : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
00066 }
00067 
00068 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
00069 
00070   bool isLocType = Loc::isLocType(castTy);
00071 
00072   if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
00073     if (isLocType)
00074       return LI->getLoc();
00075 
00076     // FIXME: Correctly support promotions/truncations.
00077     unsigned castSize = Context.getTypeSize(castTy);
00078     if (castSize == LI->getNumBits())
00079       return val;
00080     return makeLocAsInteger(LI->getLoc(), castSize);
00081   }
00082 
00083   if (const SymExpr *se = val.getAsSymbolicExpression()) {
00084     QualType T = Context.getCanonicalType(se->getType());
00085     // If types are the same or both are integers, ignore the cast.
00086     // FIXME: Remove this hack when we support symbolic truncation/extension.
00087     // HACK: If both castTy and T are integers, ignore the cast.  This is
00088     // not a permanent solution.  Eventually we want to precisely handle
00089     // extension/truncation of symbolic integers.  This prevents us from losing
00090     // precision when we assign 'x = y' and 'y' is symbolic and x and y are
00091     // different integer types.
00092    if (haveSameType(T, castTy))
00093       return val;
00094 
00095     if (!isLocType)
00096       return makeNonLoc(se, T, castTy);
00097     return UnknownVal();
00098   }
00099 
00100   // If value is a non-integer constant, produce unknown.
00101   if (!val.getAs<nonloc::ConcreteInt>())
00102     return UnknownVal();
00103 
00104   // Handle casts to a boolean type.
00105   if (castTy->isBooleanType()) {
00106     bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
00107     return makeTruthVal(b, castTy);
00108   }
00109 
00110   // Only handle casts from integers to integers - if val is an integer constant
00111   // being cast to a non-integer type, produce unknown.
00112   if (!isLocType && !castTy->isIntegralOrEnumerationType())
00113     return UnknownVal();
00114 
00115   llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
00116   BasicVals.getAPSIntType(castTy).apply(i);
00117 
00118   if (isLocType)
00119     return makeIntLocVal(i);
00120   else
00121     return makeIntVal(i);
00122 }
00123 
00124 SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
00125 
00126   // Casts from pointers -> pointers, just return the lval.
00127   //
00128   // Casts from pointers -> references, just return the lval.  These
00129   //   can be introduced by the frontend for corner cases, e.g
00130   //   casting from va_list* to __builtin_va_list&.
00131   //
00132   if (Loc::isLocType(castTy) || castTy->isReferenceType())
00133     return val;
00134 
00135   // FIXME: Handle transparent unions where a value can be "transparently"
00136   //  lifted into a union type.
00137   if (castTy->isUnionType())
00138     return UnknownVal();
00139 
00140   // Casting a Loc to a bool will almost always be true,
00141   // unless this is a weak function or a symbolic region.
00142   if (castTy->isBooleanType()) {
00143     switch (val.getSubKind()) {
00144       case loc::MemRegionKind: {
00145         const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
00146         if (const FunctionTextRegion *FTR = dyn_cast<FunctionTextRegion>(R))
00147           if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
00148             if (FD->isWeak())
00149               // FIXME: Currently we are using an extent symbol here,
00150               // because there are no generic region address metadata
00151               // symbols to use, only content metadata.
00152               return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
00153 
00154         if (const SymbolicRegion *SymR = R->getSymbolicBase())
00155           return nonloc::SymbolVal(SymR->getSymbol());
00156 
00157         // FALL-THROUGH
00158       }
00159 
00160       case loc::GotoLabelKind:
00161         // Labels and non-symbolic memory regions are always true.
00162         return makeTruthVal(true, castTy);
00163     }
00164   }
00165 
00166   if (castTy->isIntegralOrEnumerationType()) {
00167     unsigned BitWidth = Context.getTypeSize(castTy);
00168 
00169     if (!val.getAs<loc::ConcreteInt>())
00170       return makeLocAsInteger(val, BitWidth);
00171 
00172     llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
00173     BasicVals.getAPSIntType(castTy).apply(i);
00174     return makeIntVal(i);
00175   }
00176 
00177   // All other cases: return 'UnknownVal'.  This includes casting pointers
00178   // to floats, which is probably badness it itself, but this is a good
00179   // intermediate solution until we do something better.
00180   return UnknownVal();
00181 }
00182 
00183 //===----------------------------------------------------------------------===//
00184 // Transfer function for unary operators.
00185 //===----------------------------------------------------------------------===//
00186 
00187 SVal SimpleSValBuilder::evalMinus(NonLoc val) {
00188   switch (val.getSubKind()) {
00189   case nonloc::ConcreteIntKind:
00190     return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
00191   default:
00192     return UnknownVal();
00193   }
00194 }
00195 
00196 SVal SimpleSValBuilder::evalComplement(NonLoc X) {
00197   switch (X.getSubKind()) {
00198   case nonloc::ConcreteIntKind:
00199     return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
00200   default:
00201     return UnknownVal();
00202   }
00203 }
00204 
00205 //===----------------------------------------------------------------------===//
00206 // Transfer function for binary operators.
00207 //===----------------------------------------------------------------------===//
00208 
00209 SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
00210                                     BinaryOperator::Opcode op,
00211                                     const llvm::APSInt &RHS,
00212                                     QualType resultTy) {
00213   bool isIdempotent = false;
00214 
00215   // Check for a few special cases with known reductions first.
00216   switch (op) {
00217   default:
00218     // We can't reduce this case; just treat it normally.
00219     break;
00220   case BO_Mul:
00221     // a*0 and a*1
00222     if (RHS == 0)
00223       return makeIntVal(0, resultTy);
00224     else if (RHS == 1)
00225       isIdempotent = true;
00226     break;
00227   case BO_Div:
00228     // a/0 and a/1
00229     if (RHS == 0)
00230       // This is also handled elsewhere.
00231       return UndefinedVal();
00232     else if (RHS == 1)
00233       isIdempotent = true;
00234     break;
00235   case BO_Rem:
00236     // a%0 and a%1
00237     if (RHS == 0)
00238       // This is also handled elsewhere.
00239       return UndefinedVal();
00240     else if (RHS == 1)
00241       return makeIntVal(0, resultTy);
00242     break;
00243   case BO_Add:
00244   case BO_Sub:
00245   case BO_Shl:
00246   case BO_Shr:
00247   case BO_Xor:
00248     // a+0, a-0, a<<0, a>>0, a^0
00249     if (RHS == 0)
00250       isIdempotent = true;
00251     break;
00252   case BO_And:
00253     // a&0 and a&(~0)
00254     if (RHS == 0)
00255       return makeIntVal(0, resultTy);
00256     else if (RHS.isAllOnesValue())
00257       isIdempotent = true;
00258     break;
00259   case BO_Or:
00260     // a|0 and a|(~0)
00261     if (RHS == 0)
00262       isIdempotent = true;
00263     else if (RHS.isAllOnesValue()) {
00264       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
00265       return nonloc::ConcreteInt(Result);
00266     }
00267     break;
00268   }
00269 
00270   // Idempotent ops (like a*1) can still change the type of an expression.
00271   // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
00272   // dirty work.
00273   if (isIdempotent)
00274       return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
00275 
00276   // If we reach this point, the expression cannot be simplified.
00277   // Make a SymbolVal for the entire expression, after converting the RHS.
00278   const llvm::APSInt *ConvertedRHS = &RHS;
00279   if (BinaryOperator::isComparisonOp(op)) {
00280     // We're looking for a type big enough to compare the symbolic value
00281     // with the given constant.
00282     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
00283     ASTContext &Ctx = getContext();
00284     QualType SymbolType = LHS->getType();
00285     uint64_t ValWidth = RHS.getBitWidth();
00286     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
00287 
00288     if (ValWidth < TypeWidth) {
00289       // If the value is too small, extend it.
00290       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
00291     } else if (ValWidth == TypeWidth) {
00292       // If the value is signed but the symbol is unsigned, do the comparison
00293       // in unsigned space. [C99 6.3.1.8]
00294       // (For the opposite case, the value is already unsigned.)
00295       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
00296         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
00297     }
00298   } else
00299     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
00300 
00301   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
00302 }
00303 
00304 SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
00305                                   BinaryOperator::Opcode op,
00306                                   NonLoc lhs, NonLoc rhs,
00307                                   QualType resultTy)  {
00308   NonLoc InputLHS = lhs;
00309   NonLoc InputRHS = rhs;
00310 
00311   // Handle trivial case where left-side and right-side are the same.
00312   if (lhs == rhs)
00313     switch (op) {
00314       default:
00315         break;
00316       case BO_EQ:
00317       case BO_LE:
00318       case BO_GE:
00319         return makeTruthVal(true, resultTy);
00320       case BO_LT:
00321       case BO_GT:
00322       case BO_NE:
00323         return makeTruthVal(false, resultTy);
00324       case BO_Xor:
00325       case BO_Sub:
00326         if (resultTy->isIntegralOrEnumerationType())
00327           return makeIntVal(0, resultTy);
00328         return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
00329       case BO_Or:
00330       case BO_And:
00331         return evalCastFromNonLoc(lhs, resultTy);
00332     }
00333 
00334   while (1) {
00335     switch (lhs.getSubKind()) {
00336     default:
00337       return makeSymExprValNN(state, op, lhs, rhs, resultTy);
00338     case nonloc::LocAsIntegerKind: {
00339       Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
00340       switch (rhs.getSubKind()) {
00341         case nonloc::LocAsIntegerKind:
00342           return evalBinOpLL(state, op, lhsL,
00343                              rhs.castAs<nonloc::LocAsInteger>().getLoc(),
00344                              resultTy);
00345         case nonloc::ConcreteIntKind: {
00346           // Transform the integer into a location and compare.
00347           llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
00348           BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
00349           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
00350         }
00351         default:
00352           switch (op) {
00353             case BO_EQ:
00354               return makeTruthVal(false, resultTy);
00355             case BO_NE:
00356               return makeTruthVal(true, resultTy);
00357             default:
00358               // This case also handles pointer arithmetic.
00359               return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
00360           }
00361       }
00362     }
00363     case nonloc::ConcreteIntKind: {
00364       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
00365 
00366       // If we're dealing with two known constants, just perform the operation.
00367       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
00368         llvm::APSInt RHSValue = *KnownRHSValue;
00369         if (BinaryOperator::isComparisonOp(op)) {
00370           // We're looking for a type big enough to compare the two values.
00371           // FIXME: This is not correct. char + short will result in a promotion
00372           // to int. Unfortunately we have lost types by this point.
00373           APSIntType CompareType = std::max(APSIntType(LHSValue),
00374                                             APSIntType(RHSValue));
00375           CompareType.apply(LHSValue);
00376           CompareType.apply(RHSValue);
00377         } else if (!BinaryOperator::isShiftOp(op)) {
00378           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
00379           IntType.apply(LHSValue);
00380           IntType.apply(RHSValue);
00381         }
00382 
00383         const llvm::APSInt *Result =
00384           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
00385         if (!Result)
00386           return UndefinedVal();
00387 
00388         return nonloc::ConcreteInt(*Result);
00389       }
00390 
00391       // Swap the left and right sides and flip the operator if doing so
00392       // allows us to better reason about the expression (this is a form
00393       // of expression canonicalization).
00394       // While we're at it, catch some special cases for non-commutative ops.
00395       switch (op) {
00396       case BO_LT:
00397       case BO_GT:
00398       case BO_LE:
00399       case BO_GE:
00400         op = BinaryOperator::reverseComparisonOp(op);
00401         // FALL-THROUGH
00402       case BO_EQ:
00403       case BO_NE:
00404       case BO_Add:
00405       case BO_Mul:
00406       case BO_And:
00407       case BO_Xor:
00408       case BO_Or:
00409         std::swap(lhs, rhs);
00410         continue;
00411       case BO_Shr:
00412         // (~0)>>a
00413         if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
00414           return evalCastFromNonLoc(lhs, resultTy);
00415         // FALL-THROUGH
00416       case BO_Shl:
00417         // 0<<a and 0>>a
00418         if (LHSValue == 0)
00419           return evalCastFromNonLoc(lhs, resultTy);
00420         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
00421       default:
00422         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
00423       }
00424     }
00425     case nonloc::SymbolValKind: {
00426       // We only handle LHS as simple symbols or SymIntExprs.
00427       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
00428 
00429       // LHS is a symbolic expression.
00430       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
00431 
00432         // Is this a logical not? (!x is represented as x == 0.)
00433         if (op == BO_EQ && rhs.isZeroConstant()) {
00434           // We know how to negate certain expressions. Simplify them here.
00435 
00436           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
00437           switch (opc) {
00438           default:
00439             // We don't know how to negate this operation.
00440             // Just handle it as if it were a normal comparison to 0.
00441             break;
00442           case BO_LAnd:
00443           case BO_LOr:
00444             llvm_unreachable("Logical operators handled by branching logic.");
00445           case BO_Assign:
00446           case BO_MulAssign:
00447           case BO_DivAssign:
00448           case BO_RemAssign:
00449           case BO_AddAssign:
00450           case BO_SubAssign:
00451           case BO_ShlAssign:
00452           case BO_ShrAssign:
00453           case BO_AndAssign:
00454           case BO_XorAssign:
00455           case BO_OrAssign:
00456           case BO_Comma:
00457             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
00458           case BO_PtrMemD:
00459           case BO_PtrMemI:
00460             llvm_unreachable("Pointer arithmetic not handled here.");
00461           case BO_LT:
00462           case BO_GT:
00463           case BO_LE:
00464           case BO_GE:
00465           case BO_EQ:
00466           case BO_NE:
00467             assert(resultTy->isBooleanType() ||
00468                    resultTy == getConditionType());
00469             assert(symIntExpr->getType()->isBooleanType() ||
00470                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
00471                                                        getConditionType()));
00472             // Negate the comparison and make a value.
00473             opc = BinaryOperator::negateComparisonOp(opc);
00474             return makeNonLoc(symIntExpr->getLHS(), opc,
00475                 symIntExpr->getRHS(), resultTy);
00476           }
00477         }
00478 
00479         // For now, only handle expressions whose RHS is a constant.
00480         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
00481           // If both the LHS and the current expression are additive,
00482           // fold their constants and try again.
00483           if (BinaryOperator::isAdditiveOp(op)) {
00484             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
00485             if (BinaryOperator::isAdditiveOp(lop)) {
00486               // Convert the two constants to a common type, then combine them.
00487 
00488               // resultTy may not be the best type to convert to, but it's
00489               // probably the best choice in expressions with mixed type
00490               // (such as x+1U+2LL). The rules for implicit conversions should
00491               // choose a reasonable type to preserve the expression, and will
00492               // at least match how the value is going to be used.
00493               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
00494               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
00495               const llvm::APSInt &second = IntType.convert(*RHSValue);
00496 
00497               const llvm::APSInt *newRHS;
00498               if (lop == op)
00499                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
00500               else
00501                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
00502 
00503               assert(newRHS && "Invalid operation despite common type!");
00504               rhs = nonloc::ConcreteInt(*newRHS);
00505               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
00506               op = lop;
00507               continue;
00508             }
00509           }
00510 
00511           // Otherwise, make a SymIntExpr out of the expression.
00512           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
00513         }
00514       }
00515 
00516       // Does the symbolic expression simplify to a constant?
00517       // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
00518       // and try again.
00519       ConstraintManager &CMgr = state->getConstraintManager();
00520       if (const llvm::APSInt *Constant = CMgr.getSymVal(state, Sym)) {
00521         lhs = nonloc::ConcreteInt(*Constant);
00522         continue;
00523       }
00524 
00525       // Is the RHS a constant?
00526       if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
00527         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
00528 
00529       // Give up -- this is not a symbolic expression we can handle.
00530       return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
00531     }
00532     }
00533   }
00534 }
00535 
00536 static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
00537                                             const FieldRegion *RightFR,
00538                                             BinaryOperator::Opcode op,
00539                                             QualType resultTy,
00540                                             SimpleSValBuilder &SVB) {
00541   // Only comparisons are meaningful here!
00542   if (!BinaryOperator::isComparisonOp(op))
00543     return UnknownVal();
00544 
00545   // Next, see if the two FRs have the same super-region.
00546   // FIXME: This doesn't handle casts yet, and simply stripping the casts
00547   // doesn't help.
00548   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
00549     return UnknownVal();
00550 
00551   const FieldDecl *LeftFD = LeftFR->getDecl();
00552   const FieldDecl *RightFD = RightFR->getDecl();
00553   const RecordDecl *RD = LeftFD->getParent();
00554 
00555   // Make sure the two FRs are from the same kind of record. Just in case!
00556   // FIXME: This is probably where inheritance would be a problem.
00557   if (RD != RightFD->getParent())
00558     return UnknownVal();
00559 
00560   // We know for sure that the two fields are not the same, since that
00561   // would have given us the same SVal.
00562   if (op == BO_EQ)
00563     return SVB.makeTruthVal(false, resultTy);
00564   if (op == BO_NE)
00565     return SVB.makeTruthVal(true, resultTy);
00566 
00567   // Iterate through the fields and see which one comes first.
00568   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
00569   // members and the units in which bit-fields reside have addresses that
00570   // increase in the order in which they are declared."
00571   bool leftFirst = (op == BO_LT || op == BO_LE);
00572   for (const auto *I : RD->fields()) {
00573     if (I == LeftFD)
00574       return SVB.makeTruthVal(leftFirst, resultTy);
00575     if (I == RightFD)
00576       return SVB.makeTruthVal(!leftFirst, resultTy);
00577   }
00578 
00579   llvm_unreachable("Fields not found in parent record's definition");
00580 }
00581 
00582 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
00583 SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
00584                                   BinaryOperator::Opcode op,
00585                                   Loc lhs, Loc rhs,
00586                                   QualType resultTy) {
00587   // Only comparisons and subtractions are valid operations on two pointers.
00588   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
00589   // However, if a pointer is casted to an integer, evalBinOpNN may end up
00590   // calling this function with another operation (PR7527). We don't attempt to
00591   // model this for now, but it could be useful, particularly when the
00592   // "location" is actually an integer value that's been passed through a void*.
00593   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
00594     return UnknownVal();
00595 
00596   // Special cases for when both sides are identical.
00597   if (lhs == rhs) {
00598     switch (op) {
00599     default:
00600       llvm_unreachable("Unimplemented operation for two identical values");
00601     case BO_Sub:
00602       return makeZeroVal(resultTy);
00603     case BO_EQ:
00604     case BO_LE:
00605     case BO_GE:
00606       return makeTruthVal(true, resultTy);
00607     case BO_NE:
00608     case BO_LT:
00609     case BO_GT:
00610       return makeTruthVal(false, resultTy);
00611     }
00612   }
00613 
00614   switch (lhs.getSubKind()) {
00615   default:
00616     llvm_unreachable("Ordering not implemented for this Loc.");
00617 
00618   case loc::GotoLabelKind:
00619     // The only thing we know about labels is that they're non-null.
00620     if (rhs.isZeroConstant()) {
00621       switch (op) {
00622       default:
00623         break;
00624       case BO_Sub:
00625         return evalCastFromLoc(lhs, resultTy);
00626       case BO_EQ:
00627       case BO_LE:
00628       case BO_LT:
00629         return makeTruthVal(false, resultTy);
00630       case BO_NE:
00631       case BO_GT:
00632       case BO_GE:
00633         return makeTruthVal(true, resultTy);
00634       }
00635     }
00636     // There may be two labels for the same location, and a function region may
00637     // have the same address as a label at the start of the function (depending
00638     // on the ABI).
00639     // FIXME: we can probably do a comparison against other MemRegions, though.
00640     // FIXME: is there a way to tell if two labels refer to the same location?
00641     return UnknownVal(); 
00642 
00643   case loc::ConcreteIntKind: {
00644     // If one of the operands is a symbol and the other is a constant,
00645     // build an expression for use by the constraint manager.
00646     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
00647       // We can only build expressions with symbols on the left,
00648       // so we need a reversible operator.
00649       if (!BinaryOperator::isComparisonOp(op))
00650         return UnknownVal();
00651 
00652       const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
00653       op = BinaryOperator::reverseComparisonOp(op);
00654       return makeNonLoc(rSym, op, lVal, resultTy);
00655     }
00656 
00657     // If both operands are constants, just perform the operation.
00658     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
00659       SVal ResultVal =
00660           lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
00661       if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
00662         return evalCastFromNonLoc(*Result, resultTy);
00663 
00664       assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
00665       return UnknownVal();
00666     }
00667 
00668     // Special case comparisons against NULL.
00669     // This must come after the test if the RHS is a symbol, which is used to
00670     // build constraints. The address of any non-symbolic region is guaranteed
00671     // to be non-NULL, as is any label.
00672     assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
00673     if (lhs.isZeroConstant()) {
00674       switch (op) {
00675       default:
00676         break;
00677       case BO_EQ:
00678       case BO_GT:
00679       case BO_GE:
00680         return makeTruthVal(false, resultTy);
00681       case BO_NE:
00682       case BO_LT:
00683       case BO_LE:
00684         return makeTruthVal(true, resultTy);
00685       }
00686     }
00687 
00688     // Comparing an arbitrary integer to a region or label address is
00689     // completely unknowable.
00690     return UnknownVal();
00691   }
00692   case loc::MemRegionKind: {
00693     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
00694       // If one of the operands is a symbol and the other is a constant,
00695       // build an expression for use by the constraint manager.
00696       if (SymbolRef lSym = lhs.getAsLocSymbol(true))
00697         return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
00698 
00699       // Special case comparisons to NULL.
00700       // This must come after the test if the LHS is a symbol, which is used to
00701       // build constraints. The address of any non-symbolic region is guaranteed
00702       // to be non-NULL.
00703       if (rInt->isZeroConstant()) {
00704         if (op == BO_Sub)
00705           return evalCastFromLoc(lhs, resultTy);
00706 
00707         if (BinaryOperator::isComparisonOp(op)) {
00708           QualType boolType = getContext().BoolTy;
00709           NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
00710           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
00711           return evalBinOpNN(state, op, l, r, resultTy);
00712         }
00713       }
00714 
00715       // Comparing a region to an arbitrary integer is completely unknowable.
00716       return UnknownVal();
00717     }
00718 
00719     // Get both values as regions, if possible.
00720     const MemRegion *LeftMR = lhs.getAsRegion();
00721     assert(LeftMR && "MemRegionKind SVal doesn't have a region!");
00722 
00723     const MemRegion *RightMR = rhs.getAsRegion();
00724     if (!RightMR)
00725       // The RHS is probably a label, which in theory could address a region.
00726       // FIXME: we can probably make a more useful statement about non-code
00727       // regions, though.
00728       return UnknownVal();
00729 
00730     const MemRegion *LeftBase = LeftMR->getBaseRegion();
00731     const MemRegion *RightBase = RightMR->getBaseRegion();
00732     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
00733     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
00734     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
00735 
00736     // If the two regions are from different known memory spaces they cannot be
00737     // equal. Also, assume that no symbolic region (whose memory space is
00738     // unknown) is on the stack.
00739     if (LeftMS != RightMS &&
00740         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
00741          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
00742       switch (op) {
00743       default:
00744         return UnknownVal();
00745       case BO_EQ:
00746         return makeTruthVal(false, resultTy);
00747       case BO_NE:
00748         return makeTruthVal(true, resultTy);
00749       }
00750     }
00751 
00752     // If both values wrap regions, see if they're from different base regions.
00753     // Note, heap base symbolic regions are assumed to not alias with
00754     // each other; for example, we assume that malloc returns different address
00755     // on each invocation.
00756     if (LeftBase != RightBase &&
00757         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
00758          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
00759       switch (op) {
00760       default:
00761         return UnknownVal();
00762       case BO_EQ:
00763         return makeTruthVal(false, resultTy);
00764       case BO_NE:
00765         return makeTruthVal(true, resultTy);
00766       }
00767     }
00768 
00769     // Handle special cases for when both regions are element regions.
00770     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
00771     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
00772     if (RightER && LeftER) {
00773       // Next, see if the two ERs have the same super-region and matching types.
00774       // FIXME: This should do something useful even if the types don't match,
00775       // though if both indexes are constant the RegionRawOffset path will
00776       // give the correct answer.
00777       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
00778           LeftER->getElementType() == RightER->getElementType()) {
00779         // Get the left index and cast it to the correct type.
00780         // If the index is unknown or undefined, bail out here.
00781         SVal LeftIndexVal = LeftER->getIndex();
00782         Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
00783         if (!LeftIndex)
00784           return UnknownVal();
00785         LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
00786         LeftIndex = LeftIndexVal.getAs<NonLoc>();
00787         if (!LeftIndex)
00788           return UnknownVal();
00789 
00790         // Do the same for the right index.
00791         SVal RightIndexVal = RightER->getIndex();
00792         Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
00793         if (!RightIndex)
00794           return UnknownVal();
00795         RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
00796         RightIndex = RightIndexVal.getAs<NonLoc>();
00797         if (!RightIndex)
00798           return UnknownVal();
00799 
00800         // Actually perform the operation.
00801         // evalBinOpNN expects the two indexes to already be the right type.
00802         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
00803       }
00804     }
00805 
00806     // Special handling of the FieldRegions, even with symbolic offsets.
00807     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
00808     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
00809     if (RightFR && LeftFR) {
00810       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
00811                                                *this);
00812       if (!R.isUnknown())
00813         return R;
00814     }
00815 
00816     // Compare the regions using the raw offsets.
00817     RegionOffset LeftOffset = LeftMR->getAsOffset();
00818     RegionOffset RightOffset = RightMR->getAsOffset();
00819 
00820     if (LeftOffset.getRegion() != nullptr &&
00821         LeftOffset.getRegion() == RightOffset.getRegion() &&
00822         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
00823       int64_t left = LeftOffset.getOffset();
00824       int64_t right = RightOffset.getOffset();
00825 
00826       switch (op) {
00827         default:
00828           return UnknownVal();
00829         case BO_LT:
00830           return makeTruthVal(left < right, resultTy);
00831         case BO_GT:
00832           return makeTruthVal(left > right, resultTy);
00833         case BO_LE:
00834           return makeTruthVal(left <= right, resultTy);
00835         case BO_GE:
00836           return makeTruthVal(left >= right, resultTy);
00837         case BO_EQ:
00838           return makeTruthVal(left == right, resultTy);
00839         case BO_NE:
00840           return makeTruthVal(left != right, resultTy);
00841       }
00842     }
00843 
00844     // At this point we're not going to get a good answer, but we can try
00845     // conjuring an expression instead.
00846     SymbolRef LHSSym = lhs.getAsLocSymbol();
00847     SymbolRef RHSSym = rhs.getAsLocSymbol();
00848     if (LHSSym && RHSSym)
00849       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
00850 
00851     // If we get here, we have no way of comparing the regions.
00852     return UnknownVal();
00853   }
00854   }
00855 }
00856 
00857 SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
00858                                   BinaryOperator::Opcode op,
00859                                   Loc lhs, NonLoc rhs, QualType resultTy) {
00860   assert(!BinaryOperator::isComparisonOp(op) &&
00861          "arguments to comparison ops must be of the same type");
00862 
00863   // Special case: rhs is a zero constant.
00864   if (rhs.isZeroConstant())
00865     return lhs;
00866   
00867   // We are dealing with pointer arithmetic.
00868 
00869   // Handle pointer arithmetic on constant values.
00870   if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
00871     if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
00872       const llvm::APSInt &leftI = lhsInt->getValue();
00873       assert(leftI.isUnsigned());
00874       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
00875 
00876       // Convert the bitwidth of rightI.  This should deal with overflow
00877       // since we are dealing with concrete values.
00878       rightI = rightI.extOrTrunc(leftI.getBitWidth());
00879 
00880       // Offset the increment by the pointer size.
00881       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
00882       rightI *= Multiplicand;
00883       
00884       // Compute the adjusted pointer.
00885       switch (op) {
00886         case BO_Add:
00887           rightI = leftI + rightI;
00888           break;
00889         case BO_Sub:
00890           rightI = leftI - rightI;
00891           break;
00892         default:
00893           llvm_unreachable("Invalid pointer arithmetic operation");
00894       }
00895       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
00896     }
00897   }
00898 
00899   // Handle cases where 'lhs' is a region.
00900   if (const MemRegion *region = lhs.getAsRegion()) {
00901     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
00902     SVal index = UnknownVal();
00903     const MemRegion *superR = nullptr;
00904     QualType elementType;
00905 
00906     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
00907       assert(op == BO_Add || op == BO_Sub);
00908       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
00909                           getArrayIndexType());
00910       superR = elemReg->getSuperRegion();
00911       elementType = elemReg->getElementType();
00912     }
00913     else if (isa<SubRegion>(region)) {
00914       superR = region;
00915       index = rhs;
00916       if (resultTy->isAnyPointerType())
00917         elementType = resultTy->getPointeeType();
00918     }
00919 
00920     if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
00921       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
00922                                                        superR, getContext()));
00923     }
00924   }
00925   return UnknownVal();  
00926 }
00927 
00928 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
00929                                                    SVal V) {
00930   if (V.isUnknownOrUndef())
00931     return nullptr;
00932 
00933   if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
00934     return &X->getValue();
00935 
00936   if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
00937     return &X->getValue();
00938 
00939   if (SymbolRef Sym = V.getAsSymbol())
00940     return state->getConstraintManager().getSymVal(state, Sym);
00941 
00942   // FIXME: Add support for SymExprs.
00943   return nullptr;
00944 }