SimpleSValBuilder.cpp revision c838fd2ab889ffbb82c90da0cd634ef75b614b2c
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 // LHS is a simple symbol (not a symbolic expression). 521 QualType lhsType = Sym->getType(Context); 522 523 // Does the symbol simplify to a constant? If so, "fold" the constant 524 // by setting 'lhs' to a ConcreteInt and try again. 525 if (const llvm::APSInt *Constant = state->getSymVal(Sym)) { 526 lhs = nonloc::ConcreteInt(*Constant); 527 continue; 528 } 529 530 // Is the RHS a constant? 531 if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) 532 return MakeSymIntVal(Sym, op, *RHSValue, resultTy); 533 } 534 535 // Give up -- this is not a symbolic expression we can handle. 536 return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy); 537 } 538 } 539 } 540} 541 542// FIXME: all this logic will change if/when we have MemRegion::getLocation(). 543SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, 544 BinaryOperator::Opcode op, 545 Loc lhs, Loc rhs, 546 QualType resultTy) { 547 // Only comparisons and subtractions are valid operations on two pointers. 548 // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15]. 549 // However, if a pointer is casted to an integer, evalBinOpNN may end up 550 // calling this function with another operation (PR7527). We don't attempt to 551 // model this for now, but it could be useful, particularly when the 552 // "location" is actually an integer value that's been passed through a void*. 553 if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub)) 554 return UnknownVal(); 555 556 // Special cases for when both sides are identical. 557 if (lhs == rhs) { 558 switch (op) { 559 default: 560 llvm_unreachable("Unimplemented operation for two identical values"); 561 case BO_Sub: 562 return makeZeroVal(resultTy); 563 case BO_EQ: 564 case BO_LE: 565 case BO_GE: 566 return makeTruthVal(true, resultTy); 567 case BO_NE: 568 case BO_LT: 569 case BO_GT: 570 return makeTruthVal(false, resultTy); 571 } 572 } 573 574 switch (lhs.getSubKind()) { 575 default: 576 llvm_unreachable("Ordering not implemented for this Loc."); 577 578 case loc::GotoLabelKind: 579 // The only thing we know about labels is that they're non-null. 580 if (rhs.isZeroConstant()) { 581 switch (op) { 582 default: 583 break; 584 case BO_Sub: 585 return evalCastFromLoc(lhs, resultTy); 586 case BO_EQ: 587 case BO_LE: 588 case BO_LT: 589 return makeTruthVal(false, resultTy); 590 case BO_NE: 591 case BO_GT: 592 case BO_GE: 593 return makeTruthVal(true, resultTy); 594 } 595 } 596 // There may be two labels for the same location, and a function region may 597 // have the same address as a label at the start of the function (depending 598 // on the ABI). 599 // FIXME: we can probably do a comparison against other MemRegions, though. 600 // FIXME: is there a way to tell if two labels refer to the same location? 601 return UnknownVal(); 602 603 case loc::ConcreteIntKind: { 604 // If one of the operands is a symbol and the other is a constant, 605 // build an expression for use by the constraint manager. 606 if (SymbolRef rSym = rhs.getAsLocSymbol()) { 607 // We can only build expressions with symbols on the left, 608 // so we need a reversible operator. 609 if (!BinaryOperator::isComparisonOp(op)) 610 return UnknownVal(); 611 612 const llvm::APSInt &lVal = cast<loc::ConcreteInt>(lhs).getValue(); 613 return makeNonLoc(rSym, ReverseComparison(op), lVal, resultTy); 614 } 615 616 // If both operands are constants, just perform the operation. 617 if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) { 618 SVal ResultVal = cast<loc::ConcreteInt>(lhs).evalBinOp(BasicVals, op, 619 *rInt); 620 if (Loc *Result = dyn_cast<Loc>(&ResultVal)) 621 return evalCastFromLoc(*Result, resultTy); 622 else 623 return UnknownVal(); 624 } 625 626 // Special case comparisons against NULL. 627 // This must come after the test if the RHS is a symbol, which is used to 628 // build constraints. The address of any non-symbolic region is guaranteed 629 // to be non-NULL, as is any label. 630 assert(isa<loc::MemRegionVal>(rhs) || isa<loc::GotoLabel>(rhs)); 631 if (lhs.isZeroConstant()) { 632 switch (op) { 633 default: 634 break; 635 case BO_EQ: 636 case BO_GT: 637 case BO_GE: 638 return makeTruthVal(false, resultTy); 639 case BO_NE: 640 case BO_LT: 641 case BO_LE: 642 return makeTruthVal(true, resultTy); 643 } 644 } 645 646 // Comparing an arbitrary integer to a region or label address is 647 // completely unknowable. 648 return UnknownVal(); 649 } 650 case loc::MemRegionKind: { 651 if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) { 652 // If one of the operands is a symbol and the other is a constant, 653 // build an expression for use by the constraint manager. 654 if (SymbolRef lSym = lhs.getAsLocSymbol()) 655 return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy); 656 657 // Special case comparisons to NULL. 658 // This must come after the test if the LHS is a symbol, which is used to 659 // build constraints. The address of any non-symbolic region is guaranteed 660 // to be non-NULL. 661 if (rInt->isZeroConstant()) { 662 switch (op) { 663 default: 664 break; 665 case BO_Sub: 666 return evalCastFromLoc(lhs, resultTy); 667 case BO_EQ: 668 case BO_LT: 669 case BO_LE: 670 return makeTruthVal(false, resultTy); 671 case BO_NE: 672 case BO_GT: 673 case BO_GE: 674 return makeTruthVal(true, resultTy); 675 } 676 } 677 678 // Comparing a region to an arbitrary integer is completely unknowable. 679 return UnknownVal(); 680 } 681 682 // Get both values as regions, if possible. 683 const MemRegion *LeftMR = lhs.getAsRegion(); 684 assert(LeftMR && "MemRegionKind SVal doesn't have a region!"); 685 686 const MemRegion *RightMR = rhs.getAsRegion(); 687 if (!RightMR) 688 // The RHS is probably a label, which in theory could address a region. 689 // FIXME: we can probably make a more useful statement about non-code 690 // regions, though. 691 return UnknownVal(); 692 693 // If both values wrap regions, see if they're from different base regions. 694 const MemRegion *LeftBase = LeftMR->getBaseRegion(); 695 const MemRegion *RightBase = RightMR->getBaseRegion(); 696 if (LeftBase != RightBase && 697 !isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) { 698 switch (op) { 699 default: 700 return UnknownVal(); 701 case BO_EQ: 702 return makeTruthVal(false, resultTy); 703 case BO_NE: 704 return makeTruthVal(true, resultTy); 705 } 706 } 707 708 // The two regions are from the same base region. See if they're both a 709 // type of region we know how to compare. 710 const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace(); 711 const MemSpaceRegion *RightMS = RightBase->getMemorySpace(); 712 713 // Heuristic: assume that no symbolic region (whose memory space is 714 // unknown) is on the stack. 715 // FIXME: we should be able to be more precise once we can do better 716 // aliasing constraints for symbolic regions, but this is a reasonable, 717 // albeit unsound, assumption that holds most of the time. 718 if (isa<StackSpaceRegion>(LeftMS) ^ isa<StackSpaceRegion>(RightMS)) { 719 switch (op) { 720 default: 721 break; 722 case BO_EQ: 723 return makeTruthVal(false, resultTy); 724 case BO_NE: 725 return makeTruthVal(true, resultTy); 726 } 727 } 728 729 // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this 730 // ElementRegion path and the FieldRegion path below should be unified. 731 if (const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR)) { 732 // First see if the right region is also an ElementRegion. 733 const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR); 734 if (!RightER) 735 return UnknownVal(); 736 737 // Next, see if the two ERs have the same super-region and matching types. 738 // FIXME: This should do something useful even if the types don't match, 739 // though if both indexes are constant the RegionRawOffset path will 740 // give the correct answer. 741 if (LeftER->getSuperRegion() == RightER->getSuperRegion() && 742 LeftER->getElementType() == RightER->getElementType()) { 743 // Get the left index and cast it to the correct type. 744 // If the index is unknown or undefined, bail out here. 745 SVal LeftIndexVal = LeftER->getIndex(); 746 NonLoc *LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal); 747 if (!LeftIndex) 748 return UnknownVal(); 749 LeftIndexVal = evalCastFromNonLoc(*LeftIndex, resultTy); 750 LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal); 751 if (!LeftIndex) 752 return UnknownVal(); 753 754 // Do the same for the right index. 755 SVal RightIndexVal = RightER->getIndex(); 756 NonLoc *RightIndex = dyn_cast<NonLoc>(&RightIndexVal); 757 if (!RightIndex) 758 return UnknownVal(); 759 RightIndexVal = evalCastFromNonLoc(*RightIndex, resultTy); 760 RightIndex = dyn_cast<NonLoc>(&RightIndexVal); 761 if (!RightIndex) 762 return UnknownVal(); 763 764 // Actually perform the operation. 765 // evalBinOpNN expects the two indexes to already be the right type. 766 return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy); 767 } 768 769 // If the element indexes aren't comparable, see if the raw offsets are. 770 RegionRawOffset LeftOffset = LeftER->getAsArrayOffset(); 771 RegionRawOffset RightOffset = RightER->getAsArrayOffset(); 772 773 if (LeftOffset.getRegion() != NULL && 774 LeftOffset.getRegion() == RightOffset.getRegion()) { 775 CharUnits left = LeftOffset.getOffset(); 776 CharUnits right = RightOffset.getOffset(); 777 778 switch (op) { 779 default: 780 return UnknownVal(); 781 case BO_LT: 782 return makeTruthVal(left < right, resultTy); 783 case BO_GT: 784 return makeTruthVal(left > right, resultTy); 785 case BO_LE: 786 return makeTruthVal(left <= right, resultTy); 787 case BO_GE: 788 return makeTruthVal(left >= right, resultTy); 789 case BO_EQ: 790 return makeTruthVal(left == right, resultTy); 791 case BO_NE: 792 return makeTruthVal(left != right, resultTy); 793 } 794 } 795 796 // If we get here, we have no way of comparing the ElementRegions. 797 return UnknownVal(); 798 } 799 800 // See if both regions are fields of the same structure. 801 // FIXME: This doesn't handle nesting, inheritance, or Objective-C ivars. 802 if (const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR)) { 803 // Only comparisons are meaningful here! 804 if (!BinaryOperator::isComparisonOp(op)) 805 return UnknownVal(); 806 807 // First see if the right region is also a FieldRegion. 808 const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR); 809 if (!RightFR) 810 return UnknownVal(); 811 812 // Next, see if the two FRs have the same super-region. 813 // FIXME: This doesn't handle casts yet, and simply stripping the casts 814 // doesn't help. 815 if (LeftFR->getSuperRegion() != RightFR->getSuperRegion()) 816 return UnknownVal(); 817 818 const FieldDecl *LeftFD = LeftFR->getDecl(); 819 const FieldDecl *RightFD = RightFR->getDecl(); 820 const RecordDecl *RD = LeftFD->getParent(); 821 822 // Make sure the two FRs are from the same kind of record. Just in case! 823 // FIXME: This is probably where inheritance would be a problem. 824 if (RD != RightFD->getParent()) 825 return UnknownVal(); 826 827 // We know for sure that the two fields are not the same, since that 828 // would have given us the same SVal. 829 if (op == BO_EQ) 830 return makeTruthVal(false, resultTy); 831 if (op == BO_NE) 832 return makeTruthVal(true, resultTy); 833 834 // Iterate through the fields and see which one comes first. 835 // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field 836 // members and the units in which bit-fields reside have addresses that 837 // increase in the order in which they are declared." 838 bool leftFirst = (op == BO_LT || op == BO_LE); 839 for (RecordDecl::field_iterator I = RD->field_begin(), 840 E = RD->field_end(); I!=E; ++I) { 841 if (&*I == LeftFD) 842 return makeTruthVal(leftFirst, resultTy); 843 if (&*I == RightFD) 844 return makeTruthVal(!leftFirst, resultTy); 845 } 846 847 llvm_unreachable("Fields not found in parent record's definition"); 848 } 849 850 // If we get here, we have no way of comparing the regions. 851 return UnknownVal(); 852 } 853 } 854} 855 856SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state, 857 BinaryOperator::Opcode op, 858 Loc lhs, NonLoc rhs, QualType resultTy) { 859 860 // Special case: rhs is a zero constant. 861 if (rhs.isZeroConstant()) 862 return lhs; 863 864 // Special case: 'rhs' is an integer that has the same width as a pointer and 865 // we are using the integer location in a comparison. Normally this cannot be 866 // triggered, but transfer functions like those for OSCommpareAndSwapBarrier32 867 // can generate comparisons that trigger this code. 868 // FIXME: Are all locations guaranteed to have pointer width? 869 if (BinaryOperator::isComparisonOp(op)) { 870 if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) { 871 const llvm::APSInt *x = &rhsInt->getValue(); 872 ASTContext &ctx = Context; 873 if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) { 874 // Convert the signedness of the integer (if necessary). 875 if (x->isSigned()) 876 x = &getBasicValueFactory().getValue(*x, true); 877 878 return evalBinOpLL(state, op, lhs, loc::ConcreteInt(*x), resultTy); 879 } 880 } 881 } 882 883 // We are dealing with pointer arithmetic. 884 885 // Handle pointer arithmetic on constant values. 886 if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) { 887 if (loc::ConcreteInt *lhsInt = dyn_cast<loc::ConcreteInt>(&lhs)) { 888 const llvm::APSInt &leftI = lhsInt->getValue(); 889 assert(leftI.isUnsigned()); 890 llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true); 891 892 // Convert the bitwidth of rightI. This should deal with overflow 893 // since we are dealing with concrete values. 894 rightI = rightI.extOrTrunc(leftI.getBitWidth()); 895 896 // Offset the increment by the pointer size. 897 llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true); 898 rightI *= Multiplicand; 899 900 // Compute the adjusted pointer. 901 switch (op) { 902 case BO_Add: 903 rightI = leftI + rightI; 904 break; 905 case BO_Sub: 906 rightI = leftI - rightI; 907 break; 908 default: 909 llvm_unreachable("Invalid pointer arithmetic operation"); 910 } 911 return loc::ConcreteInt(getBasicValueFactory().getValue(rightI)); 912 } 913 } 914 915 // Handle cases where 'lhs' is a region. 916 if (const MemRegion *region = lhs.getAsRegion()) { 917 rhs = cast<NonLoc>(convertToArrayIndex(rhs)); 918 SVal index = UnknownVal(); 919 const MemRegion *superR = 0; 920 QualType elementType; 921 922 if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) { 923 assert(op == BO_Add || op == BO_Sub); 924 index = evalBinOpNN(state, op, elemReg->getIndex(), rhs, 925 getArrayIndexType()); 926 superR = elemReg->getSuperRegion(); 927 elementType = elemReg->getElementType(); 928 } 929 else if (isa<SubRegion>(region)) { 930 superR = region; 931 index = rhs; 932 if (const PointerType *PT = resultTy->getAs<PointerType>()) { 933 elementType = PT->getPointeeType(); 934 } 935 else { 936 const ObjCObjectPointerType *OT = 937 resultTy->getAs<ObjCObjectPointerType>(); 938 elementType = OT->getPointeeType(); 939 } 940 } 941 942 if (NonLoc *indexV = dyn_cast<NonLoc>(&index)) { 943 return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV, 944 superR, getContext())); 945 } 946 } 947 return UnknownVal(); 948} 949 950const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state, 951 SVal V) { 952 if (V.isUnknownOrUndef()) 953 return NULL; 954 955 if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V)) 956 return &X->getValue(); 957 958 if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V)) 959 return &X->getValue(); 960 961 if (SymbolRef Sym = V.getAsSymbol()) 962 return state->getSymVal(Sym); 963 964 // FIXME: Add support for SymExprs. 965 return NULL; 966} 967