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