ExprEngineC.cpp 33 KB

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