ExprEngineC.cpp 34 KB

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