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