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