ExprEngineC.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. //=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines ExprEngine's support for C expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ExprCXX.h"
  13. #include "clang/AST/DeclCXX.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. /// Optionally conjure and return a symbol for offset when processing
  20. /// an expression \p Expression.
  21. /// If \p Other is a location, conjure a symbol for \p Symbol
  22. /// (offset) if it is unknown so that memory arithmetic always
  23. /// results in an ElementRegion.
  24. /// \p Count The number of times the current basic block was visited.
  25. static SVal conjureOffsetSymbolOnLocation(
  26. SVal Symbol, SVal Other, Expr* Expression, SValBuilder &svalBuilder,
  27. unsigned Count, const LocationContext *LCtx) {
  28. QualType Ty = Expression->getType();
  29. if (Other.getAs<Loc>() &&
  30. Ty->isIntegralOrEnumerationType() &&
  31. Symbol.isUnknown()) {
  32. return svalBuilder.conjureSymbolVal(Expression, LCtx, Ty, Count);
  33. }
  34. return Symbol;
  35. }
  36. void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
  37. ExplodedNode *Pred,
  38. ExplodedNodeSet &Dst) {
  39. Expr *LHS = B->getLHS()->IgnoreParens();
  40. Expr *RHS = B->getRHS()->IgnoreParens();
  41. // FIXME: Prechecks eventually go in ::Visit().
  42. ExplodedNodeSet CheckedSet;
  43. ExplodedNodeSet Tmp2;
  44. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
  45. // With both the LHS and RHS evaluated, process the operation itself.
  46. for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
  47. it != ei; ++it) {
  48. ProgramStateRef state = (*it)->getState();
  49. const LocationContext *LCtx = (*it)->getLocationContext();
  50. SVal LeftV = state->getSVal(LHS, LCtx);
  51. SVal RightV = state->getSVal(RHS, LCtx);
  52. BinaryOperator::Opcode Op = B->getOpcode();
  53. if (Op == BO_Assign) {
  54. // EXPERIMENTAL: "Conjured" symbols.
  55. // FIXME: Handle structs.
  56. if (RightV.isUnknown()) {
  57. unsigned Count = currBldrCtx->blockCount();
  58. RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx,
  59. Count);
  60. }
  61. // Simulate the effects of a "store": bind the value of the RHS
  62. // to the L-Value represented by the LHS.
  63. SVal ExprVal = B->isGLValue() ? LeftV : RightV;
  64. evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
  65. LeftV, RightV);
  66. continue;
  67. }
  68. if (!B->isAssignmentOp()) {
  69. StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
  70. if (B->isAdditiveOp()) {
  71. // TODO: This can be removed after we enable history tracking with
  72. // SymSymExpr.
  73. unsigned Count = currBldrCtx->blockCount();
  74. RightV = conjureOffsetSymbolOnLocation(
  75. RightV, LeftV, RHS, svalBuilder, Count, LCtx);
  76. LeftV = conjureOffsetSymbolOnLocation(
  77. LeftV, RightV, LHS, svalBuilder, Count, LCtx);
  78. }
  79. // Although we don't yet model pointers-to-members, we do need to make
  80. // sure that the members of temporaries have a valid 'this' pointer for
  81. // other checks.
  82. if (B->getOpcode() == BO_PtrMemD)
  83. state = createTemporaryRegionIfNeeded(state, LCtx, LHS);
  84. // Process non-assignments except commas or short-circuited
  85. // logical expressions (LAnd and LOr).
  86. SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
  87. if (!Result.isUnknown()) {
  88. state = state->BindExpr(B, LCtx, Result);
  89. }
  90. Bldr.generateNode(B, *it, state);
  91. continue;
  92. }
  93. assert (B->isCompoundAssignmentOp());
  94. switch (Op) {
  95. default:
  96. llvm_unreachable("Invalid opcode for compound assignment.");
  97. case BO_MulAssign: Op = BO_Mul; break;
  98. case BO_DivAssign: Op = BO_Div; break;
  99. case BO_RemAssign: Op = BO_Rem; break;
  100. case BO_AddAssign: Op = BO_Add; break;
  101. case BO_SubAssign: Op = BO_Sub; break;
  102. case BO_ShlAssign: Op = BO_Shl; break;
  103. case BO_ShrAssign: Op = BO_Shr; break;
  104. case BO_AndAssign: Op = BO_And; break;
  105. case BO_XorAssign: Op = BO_Xor; break;
  106. case BO_OrAssign: Op = BO_Or; break;
  107. }
  108. // Perform a load (the LHS). This performs the checks for
  109. // null dereferences, and so on.
  110. ExplodedNodeSet Tmp;
  111. SVal location = LeftV;
  112. evalLoad(Tmp, B, LHS, *it, state, location);
  113. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
  114. ++I) {
  115. state = (*I)->getState();
  116. const LocationContext *LCtx = (*I)->getLocationContext();
  117. SVal V = state->getSVal(LHS, LCtx);
  118. // Get the computation type.
  119. QualType CTy =
  120. cast<CompoundAssignOperator>(B)->getComputationResultType();
  121. CTy = getContext().getCanonicalType(CTy);
  122. QualType CLHSTy =
  123. cast<CompoundAssignOperator>(B)->getComputationLHSType();
  124. CLHSTy = getContext().getCanonicalType(CLHSTy);
  125. QualType LTy = getContext().getCanonicalType(LHS->getType());
  126. // Promote LHS.
  127. V = svalBuilder.evalCast(V, CLHSTy, LTy);
  128. // Compute the result of the operation.
  129. SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
  130. B->getType(), CTy);
  131. // EXPERIMENTAL: "Conjured" symbols.
  132. // FIXME: Handle structs.
  133. SVal LHSVal;
  134. if (Result.isUnknown()) {
  135. // The symbolic value is actually for the type of the left-hand side
  136. // expression, not the computation type, as this is the value the
  137. // LValue on the LHS will bind to.
  138. LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy,
  139. currBldrCtx->blockCount());
  140. // However, we need to convert the symbol to the computation type.
  141. Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
  142. }
  143. else {
  144. // The left-hand side may bind to a different value then the
  145. // computation type.
  146. LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
  147. }
  148. // In C++, assignment and compound assignment operators return an
  149. // lvalue.
  150. if (B->isGLValue())
  151. state = state->BindExpr(B, LCtx, location);
  152. else
  153. state = state->BindExpr(B, LCtx, Result);
  154. evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
  155. }
  156. }
  157. // FIXME: postvisits eventually go in ::Visit()
  158. getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
  159. }
  160. void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
  161. ExplodedNodeSet &Dst) {
  162. CanQualType T = getContext().getCanonicalType(BE->getType());
  163. const BlockDecl *BD = BE->getBlockDecl();
  164. // Get the value of the block itself.
  165. SVal V = svalBuilder.getBlockPointer(BD, T,
  166. Pred->getLocationContext(),
  167. currBldrCtx->blockCount());
  168. ProgramStateRef State = Pred->getState();
  169. // If we created a new MemRegion for the block, we should explicitly bind
  170. // the captured variables.
  171. if (const BlockDataRegion *BDR =
  172. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  173. BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
  174. E = BDR->referenced_vars_end();
  175. auto CI = BD->capture_begin();
  176. auto CE = BD->capture_end();
  177. for (; I != E; ++I) {
  178. const VarRegion *capturedR = I.getCapturedRegion();
  179. const VarRegion *originalR = I.getOriginalRegion();
  180. // If the capture had a copy expression, use the result of evaluating
  181. // that expression, otherwise use the original value.
  182. // We rely on the invariant that the block declaration's capture variables
  183. // are a prefix of the BlockDataRegion's referenced vars (which may include
  184. // referenced globals, etc.) to enable fast lookup of the capture for a
  185. // given referenced var.
  186. const Expr *copyExpr = nullptr;
  187. if (CI != CE) {
  188. assert(CI->getVariable() == capturedR->getDecl());
  189. copyExpr = CI->getCopyExpr();
  190. CI++;
  191. }
  192. if (capturedR != originalR) {
  193. SVal originalV;
  194. const LocationContext *LCtx = Pred->getLocationContext();
  195. if (copyExpr) {
  196. originalV = State->getSVal(copyExpr, LCtx);
  197. } else {
  198. originalV = State->getSVal(loc::MemRegionVal(originalR));
  199. }
  200. State = State->bindLoc(loc::MemRegionVal(capturedR), originalV, LCtx);
  201. }
  202. }
  203. }
  204. ExplodedNodeSet Tmp;
  205. StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
  206. Bldr.generateNode(BE, Pred,
  207. State->BindExpr(BE, Pred->getLocationContext(), V),
  208. nullptr, ProgramPoint::PostLValueKind);
  209. // FIXME: Move all post/pre visits to ::Visit().
  210. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
  211. }
  212. ProgramStateRef ExprEngine::handleLValueBitCast(
  213. ProgramStateRef state, const Expr* Ex, const LocationContext* LCtx,
  214. QualType T, QualType ExTy, const CastExpr* CastE, StmtNodeBuilder& Bldr,
  215. ExplodedNode* Pred) {
  216. if (T->isLValueReferenceType()) {
  217. assert(!CastE->getType()->isLValueReferenceType());
  218. ExTy = getContext().getLValueReferenceType(ExTy);
  219. } else if (T->isRValueReferenceType()) {
  220. assert(!CastE->getType()->isRValueReferenceType());
  221. ExTy = getContext().getRValueReferenceType(ExTy);
  222. }
  223. // Delegate to SValBuilder to process.
  224. SVal OrigV = state->getSVal(Ex, LCtx);
  225. SVal V = svalBuilder.evalCast(OrigV, T, ExTy);
  226. // Negate the result if we're treating the boolean as a signed i1
  227. if (CastE->getCastKind() == CK_BooleanToSignedIntegral)
  228. V = evalMinus(V);
  229. state = state->BindExpr(CastE, LCtx, V);
  230. if (V.isUnknown() && !OrigV.isUnknown()) {
  231. state = escapeValue(state, OrigV, PSK_EscapeOther);
  232. }
  233. Bldr.generateNode(CastE, Pred, state);
  234. return state;
  235. }
  236. ProgramStateRef ExprEngine::handleLVectorSplat(
  237. ProgramStateRef state, const LocationContext* LCtx, const CastExpr* CastE,
  238. StmtNodeBuilder &Bldr, ExplodedNode* Pred) {
  239. // Recover some path sensitivity by conjuring a new value.
  240. QualType resultType = CastE->getType();
  241. if (CastE->isGLValue())
  242. resultType = getContext().getPointerType(resultType);
  243. SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx,
  244. resultType,
  245. currBldrCtx->blockCount());
  246. state = state->BindExpr(CastE, LCtx, result);
  247. Bldr.generateNode(CastE, Pred, state);
  248. return state;
  249. }
  250. void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
  251. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  252. ExplodedNodeSet dstPreStmt;
  253. getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
  254. if (CastE->getCastKind() == CK_LValueToRValue) {
  255. for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
  256. I!=E; ++I) {
  257. ExplodedNode *subExprNode = *I;
  258. ProgramStateRef state = subExprNode->getState();
  259. const LocationContext *LCtx = subExprNode->getLocationContext();
  260. evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
  261. }
  262. return;
  263. }
  264. // All other casts.
  265. QualType T = CastE->getType();
  266. QualType ExTy = Ex->getType();
  267. if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
  268. T = ExCast->getTypeAsWritten();
  269. StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
  270. for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
  271. I != E; ++I) {
  272. Pred = *I;
  273. ProgramStateRef state = Pred->getState();
  274. const LocationContext *LCtx = Pred->getLocationContext();
  275. switch (CastE->getCastKind()) {
  276. case CK_LValueToRValue:
  277. llvm_unreachable("LValueToRValue casts handled earlier.");
  278. case CK_ToVoid:
  279. continue;
  280. // The analyzer doesn't do anything special with these casts,
  281. // since it understands retain/release semantics already.
  282. case CK_ARCProduceObject:
  283. case CK_ARCConsumeObject:
  284. case CK_ARCReclaimReturnedObject:
  285. case CK_ARCExtendBlockObject: // Fall-through.
  286. case CK_CopyAndAutoreleaseBlockObject:
  287. // The analyser can ignore atomic casts for now, although some future
  288. // checkers may want to make certain that you're not modifying the same
  289. // value through atomic and nonatomic pointers.
  290. case CK_AtomicToNonAtomic:
  291. case CK_NonAtomicToAtomic:
  292. // True no-ops.
  293. case CK_NoOp:
  294. case CK_ConstructorConversion:
  295. case CK_UserDefinedConversion:
  296. case CK_FunctionToPointerDecay:
  297. case CK_BuiltinFnToFnPtr: {
  298. // Copy the SVal of Ex to CastE.
  299. ProgramStateRef state = Pred->getState();
  300. const LocationContext *LCtx = Pred->getLocationContext();
  301. SVal V = state->getSVal(Ex, LCtx);
  302. state = state->BindExpr(CastE, LCtx, V);
  303. Bldr.generateNode(CastE, Pred, state);
  304. continue;
  305. }
  306. case CK_MemberPointerToBoolean:
  307. case CK_PointerToBoolean: {
  308. SVal V = state->getSVal(Ex, LCtx);
  309. auto PTMSV = V.getAs<nonloc::PointerToMember>();
  310. if (PTMSV)
  311. V = svalBuilder.makeTruthVal(!PTMSV->isNullMemberPointer(), ExTy);
  312. if (V.isUndef() || PTMSV) {
  313. state = state->BindExpr(CastE, LCtx, V);
  314. Bldr.generateNode(CastE, Pred, state);
  315. continue;
  316. }
  317. // Explicitly proceed with default handler for this case cascade.
  318. state =
  319. handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
  320. continue;
  321. }
  322. case CK_Dependent:
  323. case CK_ArrayToPointerDecay:
  324. case CK_BitCast:
  325. case CK_AddressSpaceConversion:
  326. case CK_BooleanToSignedIntegral:
  327. case CK_IntegralToPointer:
  328. case CK_PointerToIntegral: {
  329. SVal V = state->getSVal(Ex, LCtx);
  330. if (V.getAs<nonloc::PointerToMember>()) {
  331. state = state->BindExpr(CastE, LCtx, UnknownVal());
  332. Bldr.generateNode(CastE, Pred, state);
  333. continue;
  334. }
  335. // Explicitly proceed with default handler for this case cascade.
  336. state =
  337. handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
  338. continue;
  339. }
  340. case CK_IntegralToBoolean:
  341. case CK_IntegralToFloating:
  342. case CK_FloatingToIntegral:
  343. case CK_FloatingToBoolean:
  344. case CK_FloatingCast:
  345. case CK_FloatingRealToComplex:
  346. case CK_FloatingComplexToReal:
  347. case CK_FloatingComplexToBoolean:
  348. case CK_FloatingComplexCast:
  349. case CK_FloatingComplexToIntegralComplex:
  350. case CK_IntegralRealToComplex:
  351. case CK_IntegralComplexToReal:
  352. case CK_IntegralComplexToBoolean:
  353. case CK_IntegralComplexCast:
  354. case CK_IntegralComplexToFloatingComplex:
  355. case CK_CPointerToObjCPointerCast:
  356. case CK_BlockPointerToObjCPointerCast:
  357. case CK_AnyPointerToBlockPointerCast:
  358. case CK_ObjCObjectLValueCast:
  359. case CK_ZeroToOCLOpaqueType:
  360. case CK_IntToOCLSampler:
  361. case CK_LValueBitCast:
  362. case CK_FixedPointCast:
  363. case CK_FixedPointToBoolean:
  364. case CK_FixedPointToIntegral:
  365. case CK_IntegralToFixedPoint: {
  366. state =
  367. handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred);
  368. continue;
  369. }
  370. case CK_IntegralCast: {
  371. // Delegate to SValBuilder to process.
  372. SVal V = state->getSVal(Ex, LCtx);
  373. V = svalBuilder.evalIntegralCast(state, V, T, ExTy);
  374. state = state->BindExpr(CastE, LCtx, V);
  375. Bldr.generateNode(CastE, Pred, state);
  376. continue;
  377. }
  378. case CK_DerivedToBase:
  379. case CK_UncheckedDerivedToBase: {
  380. // For DerivedToBase cast, delegate to the store manager.
  381. SVal val = state->getSVal(Ex, LCtx);
  382. val = getStoreManager().evalDerivedToBase(val, CastE);
  383. state = state->BindExpr(CastE, LCtx, val);
  384. Bldr.generateNode(CastE, Pred, state);
  385. continue;
  386. }
  387. // Handle C++ dyn_cast.
  388. case CK_Dynamic: {
  389. SVal val = state->getSVal(Ex, LCtx);
  390. // Compute the type of the result.
  391. QualType resultType = CastE->getType();
  392. if (CastE->isGLValue())
  393. resultType = getContext().getPointerType(resultType);
  394. bool Failed = false;
  395. // Check if the value being cast evaluates to 0.
  396. if (val.isZeroConstant())
  397. Failed = true;
  398. // Else, evaluate the cast.
  399. else
  400. val = getStoreManager().attemptDownCast(val, T, Failed);
  401. if (Failed) {
  402. if (T->isReferenceType()) {
  403. // A bad_cast exception is thrown if input value is a reference.
  404. // Currently, we model this, by generating a sink.
  405. Bldr.generateSink(CastE, Pred, state);
  406. continue;
  407. } else {
  408. // If the cast fails on a pointer, bind to 0.
  409. state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
  410. }
  411. } else {
  412. // If we don't know if the cast succeeded, conjure a new symbol.
  413. if (val.isUnknown()) {
  414. DefinedOrUnknownSVal NewSym =
  415. svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
  416. currBldrCtx->blockCount());
  417. state = state->BindExpr(CastE, LCtx, NewSym);
  418. } else
  419. // Else, bind to the derived region value.
  420. state = state->BindExpr(CastE, LCtx, val);
  421. }
  422. Bldr.generateNode(CastE, Pred, state);
  423. continue;
  424. }
  425. case CK_BaseToDerived: {
  426. SVal val = state->getSVal(Ex, LCtx);
  427. QualType resultType = CastE->getType();
  428. if (CastE->isGLValue())
  429. resultType = getContext().getPointerType(resultType);
  430. bool Failed = false;
  431. if (!val.isConstant()) {
  432. val = getStoreManager().attemptDownCast(val, T, Failed);
  433. }
  434. // Failed to cast or the result is unknown, fall back to conservative.
  435. if (Failed || val.isUnknown()) {
  436. val =
  437. svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType,
  438. currBldrCtx->blockCount());
  439. }
  440. state = state->BindExpr(CastE, LCtx, val);
  441. Bldr.generateNode(CastE, Pred, state);
  442. continue;
  443. }
  444. case CK_NullToPointer: {
  445. SVal V = svalBuilder.makeNull();
  446. state = state->BindExpr(CastE, LCtx, V);
  447. Bldr.generateNode(CastE, Pred, state);
  448. continue;
  449. }
  450. case CK_NullToMemberPointer: {
  451. SVal V = svalBuilder.getMemberPointer(nullptr);
  452. state = state->BindExpr(CastE, LCtx, V);
  453. Bldr.generateNode(CastE, Pred, state);
  454. continue;
  455. }
  456. case CK_DerivedToBaseMemberPointer:
  457. case CK_BaseToDerivedMemberPointer:
  458. case CK_ReinterpretMemberPointer: {
  459. SVal V = state->getSVal(Ex, LCtx);
  460. if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) {
  461. SVal CastedPTMSV = svalBuilder.makePointerToMember(
  462. getBasicVals().accumCXXBase(
  463. llvm::make_range<CastExpr::path_const_iterator>(
  464. CastE->path_begin(), CastE->path_end()), *PTMSV));
  465. state = state->BindExpr(CastE, LCtx, CastedPTMSV);
  466. Bldr.generateNode(CastE, Pred, state);
  467. continue;
  468. }
  469. // Explicitly proceed with default handler for this case cascade.
  470. state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
  471. continue;
  472. }
  473. // Various C++ casts that are not handled yet.
  474. case CK_ToUnion:
  475. case CK_VectorSplat: {
  476. state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred);
  477. continue;
  478. }
  479. }
  480. }
  481. }
  482. void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
  483. ExplodedNode *Pred,
  484. ExplodedNodeSet &Dst) {
  485. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  486. ProgramStateRef State = Pred->getState();
  487. const LocationContext *LCtx = Pred->getLocationContext();
  488. const Expr *Init = CL->getInitializer();
  489. SVal V = State->getSVal(CL->getInitializer(), LCtx);
  490. if (isa<CXXConstructExpr>(Init) || isa<CXXStdInitializerListExpr>(Init)) {
  491. // No work needed. Just pass the value up to this expression.
  492. } else {
  493. assert(isa<InitListExpr>(Init));
  494. Loc CLLoc = State->getLValue(CL, LCtx);
  495. State = State->bindLoc(CLLoc, V, LCtx);
  496. if (CL->isGLValue())
  497. V = CLLoc;
  498. }
  499. B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
  500. }
  501. void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
  502. ExplodedNodeSet &Dst) {
  503. // Assumption: The CFG has one DeclStmt per Decl.
  504. const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
  505. if (!VD) {
  506. //TODO:AZ: remove explicit insertion after refactoring is done.
  507. Dst.insert(Pred);
  508. return;
  509. }
  510. // FIXME: all pre/post visits should eventually be handled by ::Visit().
  511. ExplodedNodeSet dstPreVisit;
  512. getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
  513. ExplodedNodeSet dstEvaluated;
  514. StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
  515. for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
  516. I!=E; ++I) {
  517. ExplodedNode *N = *I;
  518. ProgramStateRef state = N->getState();
  519. const LocationContext *LC = N->getLocationContext();
  520. // Decls without InitExpr are not initialized explicitly.
  521. if (const Expr *InitEx = VD->getInit()) {
  522. // Note in the state that the initialization has occurred.
  523. ExplodedNode *UpdatedN = N;
  524. SVal InitVal = state->getSVal(InitEx, LC);
  525. assert(DS->isSingleDecl());
  526. if (getObjectUnderConstruction(state, DS, LC)) {
  527. state = finishObjectConstruction(state, DS, LC);
  528. // We constructed the object directly in the variable.
  529. // No need to bind anything.
  530. B.generateNode(DS, UpdatedN, state);
  531. } else {
  532. // Recover some path-sensitivity if a scalar value evaluated to
  533. // UnknownVal.
  534. if (InitVal.isUnknown()) {
  535. QualType Ty = InitEx->getType();
  536. if (InitEx->isGLValue()) {
  537. Ty = getContext().getPointerType(Ty);
  538. }
  539. InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty,
  540. currBldrCtx->blockCount());
  541. }
  542. B.takeNodes(UpdatedN);
  543. ExplodedNodeSet Dst2;
  544. evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
  545. B.addNodes(Dst2);
  546. }
  547. }
  548. else {
  549. B.generateNode(DS, N, state);
  550. }
  551. }
  552. getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
  553. }
  554. void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
  555. ExplodedNodeSet &Dst) {
  556. // This method acts upon CFG elements for logical operators && and ||
  557. // and attaches the value (true or false) to them as expressions.
  558. // It doesn't produce any state splits.
  559. // If we made it that far, we're past the point when we modeled the short
  560. // circuit. It means that we should have precise knowledge about whether
  561. // we've short-circuited. If we did, we already know the value we need to
  562. // bind. If we didn't, the value of the RHS (casted to the boolean type)
  563. // is the answer.
  564. // Currently this method tries to figure out whether we've short-circuited
  565. // by looking at the ExplodedGraph. This method is imperfect because there
  566. // could inevitably have been merges that would have resulted in multiple
  567. // potential path traversal histories. We bail out when we fail.
  568. // Due to this ambiguity, a more reliable solution would have been to
  569. // track the short circuit operation history path-sensitively until
  570. // we evaluate the respective logical operator.
  571. assert(B->getOpcode() == BO_LAnd ||
  572. B->getOpcode() == BO_LOr);
  573. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  574. ProgramStateRef state = Pred->getState();
  575. if (B->getType()->isVectorType()) {
  576. // FIXME: We do not model vector arithmetic yet. When adding support for
  577. // that, note that the CFG-based reasoning below does not apply, because
  578. // logical operators on vectors are not short-circuit. Currently they are
  579. // modeled as short-circuit in Clang CFG but this is incorrect.
  580. // Do not set the value for the expression. It'd be UnknownVal by default.
  581. Bldr.generateNode(B, Pred, state);
  582. return;
  583. }
  584. ExplodedNode *N = Pred;
  585. while (!N->getLocation().getAs<BlockEntrance>()) {
  586. ProgramPoint P = N->getLocation();
  587. assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
  588. (void) P;
  589. if (N->pred_size() != 1) {
  590. // We failed to track back where we came from.
  591. Bldr.generateNode(B, Pred, state);
  592. return;
  593. }
  594. N = *N->pred_begin();
  595. }
  596. if (N->pred_size() != 1) {
  597. // We failed to track back where we came from.
  598. Bldr.generateNode(B, Pred, state);
  599. return;
  600. }
  601. N = *N->pred_begin();
  602. BlockEdge BE = N->getLocation().castAs<BlockEdge>();
  603. SVal X;
  604. // Determine the value of the expression by introspecting how we
  605. // got this location in the CFG. This requires looking at the previous
  606. // block we were in and what kind of control-flow transfer was involved.
  607. const CFGBlock *SrcBlock = BE.getSrc();
  608. // The only terminator (if there is one) that makes sense is a logical op.
  609. CFGTerminator T = SrcBlock->getTerminator();
  610. if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
  611. (void) Term;
  612. assert(Term->isLogicalOp());
  613. assert(SrcBlock->succ_size() == 2);
  614. // Did we take the true or false branch?
  615. unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
  616. X = svalBuilder.makeIntVal(constant, B->getType());
  617. }
  618. else {
  619. // If there is no terminator, by construction the last statement
  620. // in SrcBlock is the value of the enclosing expression.
  621. // However, we still need to constrain that value to be 0 or 1.
  622. assert(!SrcBlock->empty());
  623. CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
  624. const Expr *RHS = cast<Expr>(Elem.getStmt());
  625. SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
  626. if (RHSVal.isUndef()) {
  627. X = RHSVal;
  628. } else {
  629. // We evaluate "RHSVal != 0" expression which result in 0 if the value is
  630. // known to be false, 1 if the value is known to be true and a new symbol
  631. // when the assumption is unknown.
  632. nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType()));
  633. X = evalBinOp(N->getState(), BO_NE,
  634. svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()),
  635. Zero, B->getType());
  636. }
  637. }
  638. Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
  639. }
  640. void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
  641. ExplodedNode *Pred,
  642. ExplodedNodeSet &Dst) {
  643. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  644. ProgramStateRef state = Pred->getState();
  645. const LocationContext *LCtx = Pred->getLocationContext();
  646. QualType T = getContext().getCanonicalType(IE->getType());
  647. unsigned NumInitElements = IE->getNumInits();
  648. if (!IE->isGLValue() && !IE->isTransparent() &&
  649. (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
  650. T->isAnyComplexType())) {
  651. llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
  652. // Handle base case where the initializer has no elements.
  653. // e.g: static int* myArray[] = {};
  654. if (NumInitElements == 0) {
  655. SVal V = svalBuilder.makeCompoundVal(T, vals);
  656. B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
  657. return;
  658. }
  659. for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
  660. ei = IE->rend(); it != ei; ++it) {
  661. SVal V = state->getSVal(cast<Expr>(*it), LCtx);
  662. vals = getBasicVals().prependSVal(V, vals);
  663. }
  664. B.generateNode(IE, Pred,
  665. state->BindExpr(IE, LCtx,
  666. svalBuilder.makeCompoundVal(T, vals)));
  667. return;
  668. }
  669. // Handle scalars: int{5} and int{} and GLvalues.
  670. // Note, if the InitListExpr is a GLvalue, it means that there is an address
  671. // representing it, so it must have a single init element.
  672. assert(NumInitElements <= 1);
  673. SVal V;
  674. if (NumInitElements == 0)
  675. V = getSValBuilder().makeZeroVal(T);
  676. else
  677. V = state->getSVal(IE->getInit(0), LCtx);
  678. B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
  679. }
  680. void ExprEngine::VisitGuardedExpr(const Expr *Ex,
  681. const Expr *L,
  682. const Expr *R,
  683. ExplodedNode *Pred,
  684. ExplodedNodeSet &Dst) {
  685. assert(L && R);
  686. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  687. ProgramStateRef state = Pred->getState();
  688. const LocationContext *LCtx = Pred->getLocationContext();
  689. const CFGBlock *SrcBlock = nullptr;
  690. // Find the predecessor block.
  691. ProgramStateRef SrcState = state;
  692. for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
  693. ProgramPoint PP = N->getLocation();
  694. if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
  695. // If the state N has multiple predecessors P, it means that successors
  696. // of P are all equivalent.
  697. // In turn, that means that all nodes at P are equivalent in terms
  698. // of observable behavior at N, and we can follow any of them.
  699. // FIXME: a more robust solution which does not walk up the tree.
  700. continue;
  701. }
  702. SrcBlock = PP.castAs<BlockEdge>().getSrc();
  703. SrcState = N->getState();
  704. break;
  705. }
  706. assert(SrcBlock && "missing function entry");
  707. // Find the last expression in the predecessor block. That is the
  708. // expression that is used for the value of the ternary expression.
  709. bool hasValue = false;
  710. SVal V;
  711. for (CFGElement CE : llvm::reverse(*SrcBlock)) {
  712. if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
  713. const Expr *ValEx = cast<Expr>(CS->getStmt());
  714. ValEx = ValEx->IgnoreParens();
  715. // For GNU extension '?:' operator, the left hand side will be an
  716. // OpaqueValueExpr, so get the underlying expression.
  717. if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
  718. L = OpaqueEx->getSourceExpr();
  719. // If the last expression in the predecessor block matches true or false
  720. // subexpression, get its the value.
  721. if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
  722. hasValue = true;
  723. V = SrcState->getSVal(ValEx, LCtx);
  724. }
  725. break;
  726. }
  727. }
  728. if (!hasValue)
  729. V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  730. currBldrCtx->blockCount());
  731. // Generate a new node with the binding from the appropriate path.
  732. B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
  733. }
  734. void ExprEngine::
  735. VisitOffsetOfExpr(const OffsetOfExpr *OOE,
  736. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  737. StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
  738. Expr::EvalResult Result;
  739. if (OOE->EvaluateAsInt(Result, getContext())) {
  740. APSInt IV = Result.Val.getInt();
  741. assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
  742. assert(OOE->getType()->isBuiltinType());
  743. assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
  744. assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
  745. SVal X = svalBuilder.makeIntVal(IV);
  746. B.generateNode(OOE, Pred,
  747. Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
  748. X));
  749. }
  750. // FIXME: Handle the case where __builtin_offsetof is not a constant.
  751. }
  752. void ExprEngine::
  753. VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
  754. ExplodedNode *Pred,
  755. ExplodedNodeSet &Dst) {
  756. // FIXME: Prechecks eventually go in ::Visit().
  757. ExplodedNodeSet CheckedSet;
  758. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this);
  759. ExplodedNodeSet EvalSet;
  760. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  761. QualType T = Ex->getTypeOfArgument();
  762. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  763. I != E; ++I) {
  764. if (Ex->getKind() == UETT_SizeOf) {
  765. if (!T->isIncompleteType() && !T->isConstantSizeType()) {
  766. assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
  767. // FIXME: Add support for VLA type arguments and VLA expressions.
  768. // When that happens, we should probably refactor VLASizeChecker's code.
  769. continue;
  770. } else if (T->getAs<ObjCObjectType>()) {
  771. // Some code tries to take the sizeof an ObjCObjectType, relying that
  772. // the compiler has laid out its representation. Just report Unknown
  773. // for these.
  774. continue;
  775. }
  776. }
  777. APSInt Value = Ex->EvaluateKnownConstInt(getContext());
  778. CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
  779. ProgramStateRef state = (*I)->getState();
  780. state = state->BindExpr(Ex, (*I)->getLocationContext(),
  781. svalBuilder.makeIntVal(amt.getQuantity(),
  782. Ex->getType()));
  783. Bldr.generateNode(Ex, *I, state);
  784. }
  785. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this);
  786. }
  787. void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I,
  788. const UnaryOperator *U,
  789. StmtNodeBuilder &Bldr) {
  790. // FIXME: We can probably just have some magic in Environment::getSVal()
  791. // that propagates values, instead of creating a new node here.
  792. //
  793. // Unary "+" is a no-op, similar to a parentheses. We still have places
  794. // where it may be a block-level expression, so we need to
  795. // generate an extra node that just propagates the value of the
  796. // subexpression.
  797. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  798. ProgramStateRef state = (*I)->getState();
  799. const LocationContext *LCtx = (*I)->getLocationContext();
  800. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  801. state->getSVal(Ex, LCtx)));
  802. }
  803. void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred,
  804. ExplodedNodeSet &Dst) {
  805. // FIXME: Prechecks eventually go in ::Visit().
  806. ExplodedNodeSet CheckedSet;
  807. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
  808. ExplodedNodeSet EvalSet;
  809. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  810. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  811. I != E; ++I) {
  812. switch (U->getOpcode()) {
  813. default: {
  814. Bldr.takeNodes(*I);
  815. ExplodedNodeSet Tmp;
  816. VisitIncrementDecrementOperator(U, *I, Tmp);
  817. Bldr.addNodes(Tmp);
  818. break;
  819. }
  820. case UO_Real: {
  821. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  822. // FIXME: We don't have complex SValues yet.
  823. if (Ex->getType()->isAnyComplexType()) {
  824. // Just report "Unknown."
  825. break;
  826. }
  827. // For all other types, UO_Real is an identity operation.
  828. assert (U->getType() == Ex->getType());
  829. ProgramStateRef state = (*I)->getState();
  830. const LocationContext *LCtx = (*I)->getLocationContext();
  831. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
  832. state->getSVal(Ex, LCtx)));
  833. break;
  834. }
  835. case UO_Imag: {
  836. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  837. // FIXME: We don't have complex SValues yet.
  838. if (Ex->getType()->isAnyComplexType()) {
  839. // Just report "Unknown."
  840. break;
  841. }
  842. // For all other types, UO_Imag returns 0.
  843. ProgramStateRef state = (*I)->getState();
  844. const LocationContext *LCtx = (*I)->getLocationContext();
  845. SVal X = svalBuilder.makeZeroVal(Ex->getType());
  846. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
  847. break;
  848. }
  849. case UO_AddrOf: {
  850. // Process pointer-to-member address operation.
  851. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  852. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) {
  853. const ValueDecl *VD = DRE->getDecl();
  854. if (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD)) {
  855. ProgramStateRef State = (*I)->getState();
  856. const LocationContext *LCtx = (*I)->getLocationContext();
  857. SVal SV = svalBuilder.getMemberPointer(cast<DeclaratorDecl>(VD));
  858. Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV));
  859. break;
  860. }
  861. }
  862. // Explicitly proceed with default handler for this case cascade.
  863. handleUOExtension(I, U, Bldr);
  864. break;
  865. }
  866. case UO_Plus:
  867. assert(!U->isGLValue());
  868. LLVM_FALLTHROUGH;
  869. case UO_Deref:
  870. case UO_Extension: {
  871. handleUOExtension(I, U, Bldr);
  872. break;
  873. }
  874. case UO_LNot:
  875. case UO_Minus:
  876. case UO_Not: {
  877. assert (!U->isGLValue());
  878. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  879. ProgramStateRef state = (*I)->getState();
  880. const LocationContext *LCtx = (*I)->getLocationContext();
  881. // Get the value of the subexpression.
  882. SVal V = state->getSVal(Ex, LCtx);
  883. if (V.isUnknownOrUndef()) {
  884. Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
  885. break;
  886. }
  887. switch (U->getOpcode()) {
  888. default:
  889. llvm_unreachable("Invalid Opcode.");
  890. case UO_Not:
  891. // FIXME: Do we need to handle promotions?
  892. state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
  893. break;
  894. case UO_Minus:
  895. // FIXME: Do we need to handle promotions?
  896. state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
  897. break;
  898. case UO_LNot:
  899. // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
  900. //
  901. // Note: technically we do "E == 0", but this is the same in the
  902. // transfer functions as "0 == E".
  903. SVal Result;
  904. if (Optional<Loc> LV = V.getAs<Loc>()) {
  905. Loc X = svalBuilder.makeNullWithType(Ex->getType());
  906. Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
  907. } else if (Ex->getType()->isFloatingType()) {
  908. // FIXME: handle floating point types.
  909. Result = UnknownVal();
  910. } else {
  911. nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
  912. Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
  913. U->getType());
  914. }
  915. state = state->BindExpr(U, LCtx, Result);
  916. break;
  917. }
  918. Bldr.generateNode(U, *I, state);
  919. break;
  920. }
  921. }
  922. }
  923. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
  924. }
  925. void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
  926. ExplodedNode *Pred,
  927. ExplodedNodeSet &Dst) {
  928. // Handle ++ and -- (both pre- and post-increment).
  929. assert (U->isIncrementDecrementOp());
  930. const Expr *Ex = U->getSubExpr()->IgnoreParens();
  931. const LocationContext *LCtx = Pred->getLocationContext();
  932. ProgramStateRef state = Pred->getState();
  933. SVal loc = state->getSVal(Ex, LCtx);
  934. // Perform a load.
  935. ExplodedNodeSet Tmp;
  936. evalLoad(Tmp, U, Ex, Pred, state, loc);
  937. ExplodedNodeSet Dst2;
  938. StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
  939. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
  940. state = (*I)->getState();
  941. assert(LCtx == (*I)->getLocationContext());
  942. SVal V2_untested = state->getSVal(Ex, LCtx);
  943. // Propagate unknown and undefined values.
  944. if (V2_untested.isUnknownOrUndef()) {
  945. state = state->BindExpr(U, LCtx, V2_untested);
  946. // Perform the store, so that the uninitialized value detection happens.
  947. Bldr.takeNodes(*I);
  948. ExplodedNodeSet Dst3;
  949. evalStore(Dst3, U, Ex, *I, state, loc, V2_untested);
  950. Bldr.addNodes(Dst3);
  951. continue;
  952. }
  953. DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
  954. // Handle all other values.
  955. BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
  956. // If the UnaryOperator has non-location type, use its type to create the
  957. // constant value. If the UnaryOperator has location type, create the
  958. // constant with int type and pointer width.
  959. SVal RHS;
  960. SVal Result;
  961. if (U->getType()->isAnyPointerType())
  962. RHS = svalBuilder.makeArrayIndex(1);
  963. else if (U->getType()->isIntegralOrEnumerationType())
  964. RHS = svalBuilder.makeIntVal(1, U->getType());
  965. else
  966. RHS = UnknownVal();
  967. // The use of an operand of type bool with the ++ operators is deprecated
  968. // but valid until C++17. And if the operand of the ++ operator is of type
  969. // bool, it is set to true until C++17. Note that for '_Bool', it is also
  970. // set to true when it encounters ++ operator.
  971. if (U->getType()->isBooleanType() && U->isIncrementOp())
  972. Result = svalBuilder.makeTruthVal(true, U->getType());
  973. else
  974. Result = evalBinOp(state, Op, V2, RHS, U->getType());
  975. // Conjure a new symbol if necessary to recover precision.
  976. if (Result.isUnknown()){
  977. DefinedOrUnknownSVal SymVal =
  978. svalBuilder.conjureSymbolVal(nullptr, U, LCtx,
  979. currBldrCtx->blockCount());
  980. Result = SymVal;
  981. // If the value is a location, ++/-- should always preserve
  982. // non-nullness. Check if the original value was non-null, and if so
  983. // propagate that constraint.
  984. if (Loc::isLocType(U->getType())) {
  985. DefinedOrUnknownSVal Constraint =
  986. svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
  987. if (!state->assume(Constraint, true)) {
  988. // It isn't feasible for the original value to be null.
  989. // Propagate this constraint.
  990. Constraint = svalBuilder.evalEQ(state, SymVal,
  991. svalBuilder.makeZeroVal(U->getType()));
  992. state = state->assume(Constraint, false);
  993. assert(state);
  994. }
  995. }
  996. }
  997. // Since the lvalue-to-rvalue conversion is explicit in the AST,
  998. // we bind an l-value if the operator is prefix and an lvalue (in C++).
  999. if (U->isGLValue())
  1000. state = state->BindExpr(U, LCtx, loc);
  1001. else
  1002. state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
  1003. // Perform the store.
  1004. Bldr.takeNodes(*I);
  1005. ExplodedNodeSet Dst3;
  1006. evalStore(Dst3, U, Ex, *I, state, loc, Result);
  1007. Bldr.addNodes(Dst3);
  1008. }
  1009. Dst.insert(Dst2);
  1010. }