ExprEngineC.cpp revision 5b8c69494881b7d35bc6244b4a19be0cc2eab368
1//=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- 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 ExprEngine's support for C expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/StaticAnalyzer/Core/CheckerManager.h" 15#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 16 17using namespace clang; 18using namespace ento; 19using llvm::APSInt; 20 21void ExprEngine::VisitBinaryOperator(const BinaryOperator* B, 22 ExplodedNode *Pred, 23 ExplodedNodeSet &Dst) { 24 25 Expr *LHS = B->getLHS()->IgnoreParens(); 26 Expr *RHS = B->getRHS()->IgnoreParens(); 27 28 // FIXME: Prechecks eventually go in ::Visit(). 29 ExplodedNodeSet CheckedSet; 30 ExplodedNodeSet Tmp2; 31 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this); 32 33 // With both the LHS and RHS evaluated, process the operation itself. 34 for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end(); 35 it != ei; ++it) { 36 37 ProgramStateRef state = (*it)->getState(); 38 const LocationContext *LCtx = (*it)->getLocationContext(); 39 SVal LeftV = state->getSVal(LHS, LCtx); 40 SVal RightV = state->getSVal(RHS, LCtx); 41 42 BinaryOperator::Opcode Op = B->getOpcode(); 43 44 if (Op == BO_Assign) { 45 // EXPERIMENTAL: "Conjured" symbols. 46 // FIXME: Handle structs. 47 if (RightV.isUnknown()) { 48 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 49 RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LCtx, Count); 50 } 51 // Simulate the effects of a "store": bind the value of the RHS 52 // to the L-Value represented by the LHS. 53 SVal ExprVal = B->isGLValue() ? LeftV : RightV; 54 evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal), 55 LeftV, RightV); 56 continue; 57 } 58 59 if (!B->isAssignmentOp()) { 60 StmtNodeBuilder Bldr(*it, Tmp2, *currentBuilderContext); 61 62 if (B->isAdditiveOp()) { 63 // If one of the operands is a location, conjure a symbol for the other 64 // one (offset) if it's unknown so that memory arithmetic always 65 // results in an ElementRegion. 66 // TODO: This can be removed after we enable history tracking with 67 // SymSymExpr. 68 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 69 if (isa<Loc>(LeftV) && 70 RHS->getType()->isIntegerType() && RightV.isUnknown()) { 71 RightV = svalBuilder.getConjuredSymbolVal(RHS, LCtx, 72 RHS->getType(), Count); 73 } 74 if (isa<Loc>(RightV) && 75 LHS->getType()->isIntegerType() && LeftV.isUnknown()) { 76 LeftV = svalBuilder.getConjuredSymbolVal(LHS, LCtx, 77 LHS->getType(), Count); 78 } 79 } 80 81 // Process non-assignments except commas or short-circuited 82 // logical expressions (LAnd and LOr). 83 SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType()); 84 if (Result.isUnknown()) { 85 Bldr.generateNode(B, *it, state); 86 continue; 87 } 88 89 state = state->BindExpr(B, LCtx, Result); 90 Bldr.generateNode(B, *it, state); 91 continue; 92 } 93 94 assert (B->isCompoundAssignmentOp()); 95 96 switch (Op) { 97 default: 98 llvm_unreachable("Invalid opcode for compound assignment."); 99 case BO_MulAssign: Op = BO_Mul; break; 100 case BO_DivAssign: Op = BO_Div; break; 101 case BO_RemAssign: Op = BO_Rem; break; 102 case BO_AddAssign: Op = BO_Add; break; 103 case BO_SubAssign: Op = BO_Sub; break; 104 case BO_ShlAssign: Op = BO_Shl; break; 105 case BO_ShrAssign: Op = BO_Shr; break; 106 case BO_AndAssign: Op = BO_And; break; 107 case BO_XorAssign: Op = BO_Xor; break; 108 case BO_OrAssign: Op = BO_Or; break; 109 } 110 111 // Perform a load (the LHS). This performs the checks for 112 // null dereferences, and so on. 113 ExplodedNodeSet Tmp; 114 SVal location = LeftV; 115 evalLoad(Tmp, B, LHS, *it, state, location); 116 117 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; 118 ++I) { 119 120 state = (*I)->getState(); 121 const LocationContext *LCtx = (*I)->getLocationContext(); 122 SVal V = state->getSVal(LHS, LCtx); 123 124 // Get the computation type. 125 QualType CTy = 126 cast<CompoundAssignOperator>(B)->getComputationResultType(); 127 CTy = getContext().getCanonicalType(CTy); 128 129 QualType CLHSTy = 130 cast<CompoundAssignOperator>(B)->getComputationLHSType(); 131 CLHSTy = getContext().getCanonicalType(CLHSTy); 132 133 QualType LTy = getContext().getCanonicalType(LHS->getType()); 134 135 // Promote LHS. 136 V = svalBuilder.evalCast(V, CLHSTy, LTy); 137 138 // Compute the result of the operation. 139 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy), 140 B->getType(), CTy); 141 142 // EXPERIMENTAL: "Conjured" symbols. 143 // FIXME: Handle structs. 144 145 SVal LHSVal; 146 147 if (Result.isUnknown()) { 148 149 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 150 151 // The symbolic value is actually for the type of the left-hand side 152 // expression, not the computation type, as this is the value the 153 // LValue on the LHS will bind to. 154 LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LCtx, 155 LTy, Count); 156 157 // However, we need to convert the symbol to the computation type. 158 Result = svalBuilder.evalCast(LHSVal, CTy, LTy); 159 } 160 else { 161 // The left-hand side may bind to a different value then the 162 // computation type. 163 LHSVal = svalBuilder.evalCast(Result, LTy, CTy); 164 } 165 166 // In C++, assignment and compound assignment operators return an 167 // lvalue. 168 if (B->isGLValue()) 169 state = state->BindExpr(B, LCtx, location); 170 else 171 state = state->BindExpr(B, LCtx, Result); 172 173 evalStore(Tmp2, B, LHS, *I, state, location, LHSVal); 174 } 175 } 176 177 // FIXME: postvisits eventually go in ::Visit() 178 getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this); 179} 180 181void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 182 ExplodedNodeSet &Dst) { 183 184 CanQualType T = getContext().getCanonicalType(BE->getType()); 185 186 // Get the value of the block itself. 187 SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T, 188 Pred->getLocationContext()); 189 190 ProgramStateRef State = Pred->getState(); 191 192 // If we created a new MemRegion for the block, we should explicitly bind 193 // the captured variables. 194 if (const BlockDataRegion *BDR = 195 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) { 196 197 BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(), 198 E = BDR->referenced_vars_end(); 199 200 for (; I != E; ++I) { 201 const MemRegion *capturedR = I.getCapturedRegion(); 202 const MemRegion *originalR = I.getOriginalRegion(); 203 if (capturedR != originalR) { 204 SVal originalV = State->getSVal(loc::MemRegionVal(originalR)); 205 State = State->bindLoc(loc::MemRegionVal(capturedR), originalV); 206 } 207 } 208 } 209 210 ExplodedNodeSet Tmp; 211 StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext); 212 Bldr.generateNode(BE, Pred, 213 State->BindExpr(BE, Pred->getLocationContext(), V), 214 false, 0, 215 ProgramPoint::PostLValueKind); 216 217 // FIXME: Move all post/pre visits to ::Visit(). 218 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this); 219} 220 221void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, 222 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 223 224 ExplodedNodeSet dstPreStmt; 225 getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this); 226 227 if (CastE->getCastKind() == CK_LValueToRValue) { 228 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 229 I!=E; ++I) { 230 ExplodedNode *subExprNode = *I; 231 ProgramStateRef state = subExprNode->getState(); 232 const LocationContext *LCtx = subExprNode->getLocationContext(); 233 evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx)); 234 } 235 return; 236 } 237 238 // All other casts. 239 QualType T = CastE->getType(); 240 QualType ExTy = Ex->getType(); 241 242 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE)) 243 T = ExCast->getTypeAsWritten(); 244 245 StmtNodeBuilder Bldr(dstPreStmt, Dst, *currentBuilderContext); 246 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 247 I != E; ++I) { 248 249 Pred = *I; 250 251 switch (CastE->getCastKind()) { 252 case CK_LValueToRValue: 253 llvm_unreachable("LValueToRValue casts handled earlier."); 254 case CK_ToVoid: 255 continue; 256 // The analyzer doesn't do anything special with these casts, 257 // since it understands retain/release semantics already. 258 case CK_ARCProduceObject: 259 case CK_ARCConsumeObject: 260 case CK_ARCReclaimReturnedObject: 261 case CK_ARCExtendBlockObject: // Fall-through. 262 case CK_CopyAndAutoreleaseBlockObject: 263 // The analyser can ignore atomic casts for now, although some future 264 // checkers may want to make certain that you're not modifying the same 265 // value through atomic and nonatomic pointers. 266 case CK_AtomicToNonAtomic: 267 case CK_NonAtomicToAtomic: 268 // True no-ops. 269 case CK_NoOp: 270 case CK_FunctionToPointerDecay: { 271 // Copy the SVal of Ex to CastE. 272 ProgramStateRef state = Pred->getState(); 273 const LocationContext *LCtx = Pred->getLocationContext(); 274 SVal V = state->getSVal(Ex, LCtx); 275 state = state->BindExpr(CastE, LCtx, V); 276 Bldr.generateNode(CastE, Pred, state); 277 continue; 278 } 279 case CK_Dependent: 280 case CK_ArrayToPointerDecay: 281 case CK_BitCast: 282 case CK_IntegralCast: 283 case CK_NullToPointer: 284 case CK_IntegralToPointer: 285 case CK_PointerToIntegral: 286 case CK_PointerToBoolean: 287 case CK_IntegralToBoolean: 288 case CK_IntegralToFloating: 289 case CK_FloatingToIntegral: 290 case CK_FloatingToBoolean: 291 case CK_FloatingCast: 292 case CK_FloatingRealToComplex: 293 case CK_FloatingComplexToReal: 294 case CK_FloatingComplexToBoolean: 295 case CK_FloatingComplexCast: 296 case CK_FloatingComplexToIntegralComplex: 297 case CK_IntegralRealToComplex: 298 case CK_IntegralComplexToReal: 299 case CK_IntegralComplexToBoolean: 300 case CK_IntegralComplexCast: 301 case CK_IntegralComplexToFloatingComplex: 302 case CK_CPointerToObjCPointerCast: 303 case CK_BlockPointerToObjCPointerCast: 304 case CK_AnyPointerToBlockPointerCast: 305 case CK_ObjCObjectLValueCast: { 306 // Delegate to SValBuilder to process. 307 ProgramStateRef state = Pred->getState(); 308 const LocationContext *LCtx = Pred->getLocationContext(); 309 SVal V = state->getSVal(Ex, LCtx); 310 V = svalBuilder.evalCast(V, T, ExTy); 311 state = state->BindExpr(CastE, LCtx, V); 312 Bldr.generateNode(CastE, Pred, state); 313 continue; 314 } 315 case CK_DerivedToBase: 316 case CK_UncheckedDerivedToBase: { 317 // For DerivedToBase cast, delegate to the store manager. 318 ProgramStateRef state = Pred->getState(); 319 const LocationContext *LCtx = Pred->getLocationContext(); 320 SVal val = state->getSVal(Ex, LCtx); 321 val = getStoreManager().evalDerivedToBase(val, T); 322 state = state->BindExpr(CastE, LCtx, val); 323 Bldr.generateNode(CastE, Pred, state); 324 continue; 325 } 326 // Handle C++ dyn_cast. 327 case CK_Dynamic: { 328 ProgramStateRef state = Pred->getState(); 329 const LocationContext *LCtx = Pred->getLocationContext(); 330 SVal val = state->getSVal(Ex, LCtx); 331 332 // Compute the type of the result. 333 QualType resultType = CastE->getType(); 334 if (CastE->isGLValue()) 335 resultType = getContext().getPointerType(resultType); 336 337 bool Failed = false; 338 339 // Check if the value being cast evaluates to 0. 340 if (val.isZeroConstant()) 341 Failed = true; 342 // Else, evaluate the cast. 343 else 344 val = getStoreManager().evalDynamicCast(val, T, Failed); 345 346 if (Failed) { 347 if (T->isReferenceType()) { 348 // A bad_cast exception is thrown if input value is a reference. 349 // Currently, we model this, by generating a sink. 350 Bldr.generateNode(CastE, Pred, state, true); 351 continue; 352 } else { 353 // If the cast fails on a pointer, bind to 0. 354 state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull()); 355 } 356 } else { 357 // If we don't know if the cast succeeded, conjure a new symbol. 358 if (val.isUnknown()) { 359 DefinedOrUnknownSVal NewSym = svalBuilder.getConjuredSymbolVal(NULL, 360 CastE, LCtx, resultType, 361 currentBuilderContext->getCurrentBlockCount()); 362 state = state->BindExpr(CastE, LCtx, NewSym); 363 } else 364 // Else, bind to the derived region value. 365 state = state->BindExpr(CastE, LCtx, val); 366 } 367 Bldr.generateNode(CastE, Pred, state); 368 continue; 369 } 370 // Various C++ casts that are not handled yet. 371 case CK_ToUnion: 372 case CK_BaseToDerived: 373 case CK_NullToMemberPointer: 374 case CK_BaseToDerivedMemberPointer: 375 case CK_DerivedToBaseMemberPointer: 376 case CK_ReinterpretMemberPointer: 377 case CK_UserDefinedConversion: 378 case CK_ConstructorConversion: 379 case CK_VectorSplat: 380 case CK_MemberPointerToBoolean: 381 case CK_LValueBitCast: { 382 // Recover some path-sensitivty by conjuring a new value. 383 QualType resultType = CastE->getType(); 384 if (CastE->isGLValue()) 385 resultType = getContext().getPointerType(resultType); 386 const LocationContext *LCtx = Pred->getLocationContext(); 387 SVal result = svalBuilder.getConjuredSymbolVal(NULL, CastE, LCtx, 388 resultType, currentBuilderContext->getCurrentBlockCount()); 389 ProgramStateRef state = Pred->getState()->BindExpr(CastE, LCtx, 390 result); 391 Bldr.generateNode(CastE, Pred, state); 392 continue; 393 } 394 } 395 } 396} 397 398void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, 399 ExplodedNode *Pred, 400 ExplodedNodeSet &Dst) { 401 StmtNodeBuilder B(Pred, Dst, *currentBuilderContext); 402 403 const InitListExpr *ILE 404 = cast<InitListExpr>(CL->getInitializer()->IgnoreParens()); 405 406 ProgramStateRef state = Pred->getState(); 407 SVal ILV = state->getSVal(ILE, Pred->getLocationContext()); 408 const LocationContext *LC = Pred->getLocationContext(); 409 state = state->bindCompoundLiteral(CL, LC, ILV); 410 411 if (CL->isGLValue()) 412 B.generateNode(CL, Pred, state->BindExpr(CL, LC, state->getLValue(CL, LC))); 413 else 414 B.generateNode(CL, Pred, state->BindExpr(CL, LC, ILV)); 415} 416 417void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 418 ExplodedNodeSet &Dst) { 419 420 // FIXME: static variables may have an initializer, but the second 421 // time a function is called those values may not be current. 422 // This may need to be reflected in the CFG. 423 424 // Assumption: The CFG has one DeclStmt per Decl. 425 const Decl *D = *DS->decl_begin(); 426 427 if (!D || !isa<VarDecl>(D)) { 428 //TODO:AZ: remove explicit insertion after refactoring is done. 429 Dst.insert(Pred); 430 return; 431 } 432 433 // FIXME: all pre/post visits should eventually be handled by ::Visit(). 434 ExplodedNodeSet dstPreVisit; 435 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this); 436 437 StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext); 438 const VarDecl *VD = dyn_cast<VarDecl>(D); 439 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end(); 440 I!=E; ++I) { 441 ExplodedNode *N = *I; 442 ProgramStateRef state = N->getState(); 443 444 // Decls without InitExpr are not initialized explicitly. 445 const LocationContext *LC = N->getLocationContext(); 446 447 if (const Expr *InitEx = VD->getInit()) { 448 SVal InitVal = state->getSVal(InitEx, Pred->getLocationContext()); 449 450 // We bound the temp obj region to the CXXConstructExpr. Now recover 451 // the lazy compound value when the variable is not a reference. 452 if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() && 453 !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){ 454 InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion()); 455 assert(isa<nonloc::LazyCompoundVal>(InitVal)); 456 } 457 458 // Recover some path-sensitivity if a scalar value evaluated to 459 // UnknownVal. 460 if (InitVal.isUnknown()) { 461 QualType Ty = InitEx->getType(); 462 if (InitEx->isGLValue()) { 463 Ty = getContext().getPointerType(Ty); 464 } 465 466 InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx, LC, Ty, 467 currentBuilderContext->getCurrentBlockCount()); 468 } 469 B.takeNodes(N); 470 ExplodedNodeSet Dst2; 471 evalBind(Dst2, DS, N, state->getLValue(VD, LC), InitVal, true); 472 B.addNodes(Dst2); 473 } 474 else { 475 B.generateNode(DS, N,state->bindDeclWithNoInit(state->getRegion(VD, LC))); 476 } 477 } 478} 479 480void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, 481 ExplodedNodeSet &Dst) { 482 assert(B->getOpcode() == BO_LAnd || 483 B->getOpcode() == BO_LOr); 484 485 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 486 ProgramStateRef state = Pred->getState(); 487 const LocationContext *LCtx = Pred->getLocationContext(); 488 SVal X = state->getSVal(B, LCtx); 489 assert(X.isUndef()); 490 491 const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData(); 492 assert(Ex); 493 494 if (Ex == B->getRHS()) { 495 X = state->getSVal(Ex, LCtx); 496 497 // Handle undefined values. 498 if (X.isUndef()) { 499 Bldr.generateNode(B, Pred, state->BindExpr(B, LCtx, X)); 500 return; 501 } 502 503 DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X); 504 505 // We took the RHS. Because the value of the '&&' or '||' expression must 506 // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0 507 // or 1. Alternatively, we could take a lazy approach, and calculate this 508 // value later when necessary. We don't have the machinery in place for 509 // this right now, and since most logical expressions are used for branches, 510 // the payoff is not likely to be large. Instead, we do eager evaluation. 511 if (ProgramStateRef newState = state->assume(XD, true)) 512 Bldr.generateNode(B, Pred, 513 newState->BindExpr(B, LCtx, 514 svalBuilder.makeIntVal(1U, B->getType()))); 515 516 if (ProgramStateRef newState = state->assume(XD, false)) 517 Bldr.generateNode(B, Pred, 518 newState->BindExpr(B, LCtx, 519 svalBuilder.makeIntVal(0U, B->getType()))); 520 } 521 else { 522 // We took the LHS expression. Depending on whether we are '&&' or 523 // '||' we know what the value of the expression is via properties of 524 // the short-circuiting. 525 X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U, 526 B->getType()); 527 Bldr.generateNode(B, Pred, state->BindExpr(B, LCtx, X)); 528 } 529} 530 531void ExprEngine::VisitInitListExpr(const InitListExpr *IE, 532 ExplodedNode *Pred, 533 ExplodedNodeSet &Dst) { 534 StmtNodeBuilder B(Pred, Dst, *currentBuilderContext); 535 536 ProgramStateRef state = Pred->getState(); 537 const LocationContext *LCtx = Pred->getLocationContext(); 538 QualType T = getContext().getCanonicalType(IE->getType()); 539 unsigned NumInitElements = IE->getNumInits(); 540 541 if (T->isArrayType() || T->isRecordType() || T->isVectorType()) { 542 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList(); 543 544 // Handle base case where the initializer has no elements. 545 // e.g: static int* myArray[] = {}; 546 if (NumInitElements == 0) { 547 SVal V = svalBuilder.makeCompoundVal(T, vals); 548 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V)); 549 return; 550 } 551 552 for (InitListExpr::const_reverse_iterator it = IE->rbegin(), 553 ei = IE->rend(); it != ei; ++it) { 554 vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it), LCtx), 555 vals); 556 } 557 558 B.generateNode(IE, Pred, 559 state->BindExpr(IE, LCtx, 560 svalBuilder.makeCompoundVal(T, vals))); 561 return; 562 } 563 564 if (Loc::isLocType(T) || T->isIntegerType()) { 565 assert(IE->getNumInits() == 1); 566 const Expr *initEx = IE->getInit(0); 567 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, 568 state->getSVal(initEx, LCtx))); 569 return; 570 } 571 572 assert(IE->getNumInits() == 1); 573 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, UnknownVal())); 574 return; 575} 576 577void ExprEngine::VisitGuardedExpr(const Expr *Ex, 578 const Expr *L, 579 const Expr *R, 580 ExplodedNode *Pred, 581 ExplodedNodeSet &Dst) { 582 StmtNodeBuilder B(Pred, Dst, *currentBuilderContext); 583 584 ProgramStateRef state = Pred->getState(); 585 const LocationContext *LCtx = Pred->getLocationContext(); 586 SVal X = state->getSVal(Ex, LCtx); 587 assert (X.isUndef()); 588 const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData(); 589 assert(SE); 590 X = state->getSVal(SE, LCtx); 591 592 // Make sure that we invalidate the previous binding. 593 B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, X, true)); 594} 595 596void ExprEngine:: 597VisitOffsetOfExpr(const OffsetOfExpr *OOE, 598 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 599 StmtNodeBuilder B(Pred, Dst, *currentBuilderContext); 600 APSInt IV; 601 if (OOE->EvaluateAsInt(IV, getContext())) { 602 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType())); 603 assert(OOE->getType()->isIntegerType()); 604 assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType()); 605 SVal X = svalBuilder.makeIntVal(IV); 606 B.generateNode(OOE, Pred, 607 Pred->getState()->BindExpr(OOE, Pred->getLocationContext(), 608 X)); 609 } 610 // FIXME: Handle the case where __builtin_offsetof is not a constant. 611} 612 613 614void ExprEngine:: 615VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 616 ExplodedNode *Pred, 617 ExplodedNodeSet &Dst) { 618 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 619 620 QualType T = Ex->getTypeOfArgument(); 621 622 if (Ex->getKind() == UETT_SizeOf) { 623 if (!T->isIncompleteType() && !T->isConstantSizeType()) { 624 assert(T->isVariableArrayType() && "Unknown non-constant-sized type."); 625 626 // FIXME: Add support for VLA type arguments and VLA expressions. 627 // When that happens, we should probably refactor VLASizeChecker's code. 628 return; 629 } 630 else if (T->getAs<ObjCObjectType>()) { 631 // Some code tries to take the sizeof an ObjCObjectType, relying that 632 // the compiler has laid out its representation. Just report Unknown 633 // for these. 634 return; 635 } 636 } 637 638 APSInt Value = Ex->EvaluateKnownConstInt(getContext()); 639 CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue()); 640 641 ProgramStateRef state = Pred->getState(); 642 state = state->BindExpr(Ex, Pred->getLocationContext(), 643 svalBuilder.makeIntVal(amt.getQuantity(), 644 Ex->getType())); 645 Bldr.generateNode(Ex, Pred, state); 646} 647 648void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, 649 ExplodedNode *Pred, 650 ExplodedNodeSet &Dst) { 651 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 652 switch (U->getOpcode()) { 653 default: { 654 Bldr.takeNodes(Pred); 655 ExplodedNodeSet Tmp; 656 VisitIncrementDecrementOperator(U, Pred, Tmp); 657 Bldr.addNodes(Tmp); 658 } 659 break; 660 case UO_Real: { 661 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 662 663 // FIXME: We don't have complex SValues yet. 664 if (Ex->getType()->isAnyComplexType()) { 665 // Just report "Unknown." 666 break; 667 } 668 669 // For all other types, UO_Real is an identity operation. 670 assert (U->getType() == Ex->getType()); 671 ProgramStateRef state = Pred->getState(); 672 const LocationContext *LCtx = Pred->getLocationContext(); 673 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, 674 state->getSVal(Ex, LCtx))); 675 break; 676 } 677 678 case UO_Imag: { 679 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 680 // FIXME: We don't have complex SValues yet. 681 if (Ex->getType()->isAnyComplexType()) { 682 // Just report "Unknown." 683 break; 684 } 685 // For all other types, UO_Imag returns 0. 686 ProgramStateRef state = Pred->getState(); 687 const LocationContext *LCtx = Pred->getLocationContext(); 688 SVal X = svalBuilder.makeZeroVal(Ex->getType()); 689 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, X)); 690 break; 691 } 692 693 case UO_Plus: 694 assert(!U->isGLValue()); 695 // FALL-THROUGH. 696 case UO_Deref: 697 case UO_AddrOf: 698 case UO_Extension: { 699 // FIXME: We can probably just have some magic in Environment::getSVal() 700 // that propagates values, instead of creating a new node here. 701 // 702 // Unary "+" is a no-op, similar to a parentheses. We still have places 703 // where it may be a block-level expression, so we need to 704 // generate an extra node that just propagates the value of the 705 // subexpression. 706 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 707 ProgramStateRef state = Pred->getState(); 708 const LocationContext *LCtx = Pred->getLocationContext(); 709 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, 710 state->getSVal(Ex, LCtx))); 711 break; 712 } 713 714 case UO_LNot: 715 case UO_Minus: 716 case UO_Not: { 717 assert (!U->isGLValue()); 718 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 719 ProgramStateRef state = Pred->getState(); 720 const LocationContext *LCtx = Pred->getLocationContext(); 721 722 // Get the value of the subexpression. 723 SVal V = state->getSVal(Ex, LCtx); 724 725 if (V.isUnknownOrUndef()) { 726 Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, V)); 727 break; 728 } 729 730 switch (U->getOpcode()) { 731 default: 732 llvm_unreachable("Invalid Opcode."); 733 case UO_Not: 734 // FIXME: Do we need to handle promotions? 735 state = state->BindExpr(U, LCtx, evalComplement(cast<NonLoc>(V))); 736 break; 737 case UO_Minus: 738 // FIXME: Do we need to handle promotions? 739 state = state->BindExpr(U, LCtx, evalMinus(cast<NonLoc>(V))); 740 break; 741 case UO_LNot: 742 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." 743 // 744 // Note: technically we do "E == 0", but this is the same in the 745 // transfer functions as "0 == E". 746 SVal Result; 747 if (isa<Loc>(V)) { 748 Loc X = svalBuilder.makeNull(); 749 Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X, 750 U->getType()); 751 } 752 else { 753 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); 754 Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X, 755 U->getType()); 756 } 757 758 state = state->BindExpr(U, LCtx, Result); 759 break; 760 } 761 Bldr.generateNode(U, Pred, state); 762 break; 763 } 764 } 765 766} 767 768void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U, 769 ExplodedNode *Pred, 770 ExplodedNodeSet &Dst) { 771 // Handle ++ and -- (both pre- and post-increment). 772 assert (U->isIncrementDecrementOp()); 773 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 774 775 const LocationContext *LCtx = Pred->getLocationContext(); 776 ProgramStateRef state = Pred->getState(); 777 SVal loc = state->getSVal(Ex, LCtx); 778 779 // Perform a load. 780 ExplodedNodeSet Tmp; 781 evalLoad(Tmp, U, Ex, Pred, state, loc); 782 783 ExplodedNodeSet Dst2; 784 StmtNodeBuilder Bldr(Tmp, Dst2, *currentBuilderContext); 785 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) { 786 787 state = (*I)->getState(); 788 assert(LCtx == (*I)->getLocationContext()); 789 SVal V2_untested = state->getSVal(Ex, LCtx); 790 791 // Propagate unknown and undefined values. 792 if (V2_untested.isUnknownOrUndef()) { 793 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested)); 794 continue; 795 } 796 DefinedSVal V2 = cast<DefinedSVal>(V2_untested); 797 798 // Handle all other values. 799 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub; 800 801 // If the UnaryOperator has non-location type, use its type to create the 802 // constant value. If the UnaryOperator has location type, create the 803 // constant with int type and pointer width. 804 SVal RHS; 805 806 if (U->getType()->isAnyPointerType()) 807 RHS = svalBuilder.makeArrayIndex(1); 808 else 809 RHS = svalBuilder.makeIntVal(1, U->getType()); 810 811 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType()); 812 813 // Conjure a new symbol if necessary to recover precision. 814 if (Result.isUnknown()){ 815 DefinedOrUnknownSVal SymVal = 816 svalBuilder.getConjuredSymbolVal(NULL, Ex, LCtx, 817 currentBuilderContext->getCurrentBlockCount()); 818 Result = SymVal; 819 820 // If the value is a location, ++/-- should always preserve 821 // non-nullness. Check if the original value was non-null, and if so 822 // propagate that constraint. 823 if (Loc::isLocType(U->getType())) { 824 DefinedOrUnknownSVal Constraint = 825 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType())); 826 827 if (!state->assume(Constraint, true)) { 828 // It isn't feasible for the original value to be null. 829 // Propagate this constraint. 830 Constraint = svalBuilder.evalEQ(state, SymVal, 831 svalBuilder.makeZeroVal(U->getType())); 832 833 834 state = state->assume(Constraint, false); 835 assert(state); 836 } 837 } 838 } 839 840 // Since the lvalue-to-rvalue conversion is explicit in the AST, 841 // we bind an l-value if the operator is prefix and an lvalue (in C++). 842 if (U->isGLValue()) 843 state = state->BindExpr(U, LCtx, loc); 844 else 845 state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result); 846 847 // Perform the store. 848 Bldr.takeNodes(*I); 849 ExplodedNodeSet Dst3; 850 evalStore(Dst3, U, U, *I, state, loc, Result); 851 Bldr.addNodes(Dst3); 852 } 853 Dst.insert(Dst2); 854} 855