SimpleSValBuilder.cpp 40 KB

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